script_21.py - Zip Two Lists Together
Code
#!/usr/bin/env python3
"""Zip two lists together"""
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Explanation
Line 4-5: Two parallel lists
- names is list of strings
- ages is list of integers
- Same length (3 elements each)
- Related data at same indices
Line 7: for name, age in zip(names, ages):
- zip() is built-in function that combines multiple iterables
- Takes two (or more) iterables as arguments
- Returns tuples pairing corresponding elements
- Creates: ("Alice", 25), ("Bob", 30), ("Charlie", 35)
- Tuple unpacking: name, age extracts both values
- name gets element from first list (string)
- age gets element from second list (integer)
- Stops when shortest iterable is exhausted
- Better than using indices: for i in range(len(names)): name=names[i], age=ages[i]
Line 8: print(f"{name} is {age} years old")
- Both variables from tuple unpacking available
- Combines related data from parallel lists