What it does
zip() combines multiple sequences (lists, tuples, etc.) into pairs (or tuples) of corresponding elements. It stops when the shortest sequence ends.
Basic usage
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
# Loop over both lists together:
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# Output:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old
Creating pairs
names = ['Alice', 'Bob']
ages = [25, 30]
# Convert to list of tuples:
pairs = list(zip(names, ages))
print(pairs) # [('Alice', 25), ('Bob', 30)]
Different lengths
zip stops at the shortest sequence:
list1 = [1, 2, 3, 4]
list2 = ['a', 'b']
for x, y in zip(list1, list2):
print(x, y)
# Output:
# 1 a
# 2 b
# (stops here, ignores 3 and 4)
Unzipping
Use * to "unzip" back into separate lists:
pairs = [('Alice', 25), ('Bob', 30)]
names, ages = zip(*pairs)
print(names) # ('Alice', 'Bob')
print(ages) # (25, 30)
When to use zip
- Looping over multiple lists simultaneously
- Creating dictionaries from two lists
- Processing related data in parallel
- Transposing data (rows to columns)