zip()
Pairs up items from two or more lists by position, so you can loop over them together, build a dictionary, or split pairs apart again.
zip(*iterables, strict=False)zip() walks through several collections at once and groups their items by position: the first items together, then the second items, and so on. Each group is a tuple.
The classic use is a loop over two lists that belong together: for name, score in zip(names, scores):. It also builds a dictionary in one step: dict(zip(keys, values)).
If the lists have different lengths, zip() stops at the shortest one and silently drops the rest. That can hide a bug. From Python 3.10, strict=True makes it raise an error instead; itertools.zip_longest() keeps going and fills the gaps.
Parameters
| Parameter | What it is |
|---|---|
*iterablesrequired | Two or more things to loop over (one or none also work). Lists, tuples, strings, ranges, files… |
strictoptional, default False | Python 3.10+. When True, raise ValueError if the iterables do not all have the same length. |
Return value
A zip object that produces tuples. It is an iterator: wrap it in list() to see the items, and remember it can be used only once.
Examples
1Loop over two lists together
names = ["Lena", "Omar", "Yuki"]
scores = [88, 92, 79]
for name, score in zip(names, scores):
print(f"{name}: {score}")Lena: 88 Omar: 92 Yuki: 79
2Build a dictionary from two lists
fields = ["name", "city", "age"]
values = ["Maria", "Lisbon", "34"]
person = dict(zip(fields, values))
print(person){'name': 'Maria', 'city': 'Lisbon', 'age': '34'}3Line totals from three lists
items = ["bread", "milk", "eggs"]
prices = [2.40, 1.15, 3.60]
qty = [2, 3, 1]
for item, price, q in zip(items, prices, qty):
print(f"{item:<6} {q} x {price:.2f} = {price * q:.2f}")bread 2 x 2.40 = 4.80 milk 3 x 1.15 = 3.45 eggs 1 x 3.60 = 3.60
4Different lengths: shortest wins
days = ["Mon", "Tue", "Wed"]
temps = [18, 21]
print(list(zip(days, temps)))
try:
list(zip(days, temps, strict=True))
except ValueError:
print("ValueError: the lists have different lengths")[('Mon', 18), ('Tue', 21)]
ValueError: the lists have different lengthsWed was dropped without a word. strict=True turns that into an error you can see.
5Unzip pairs and turn rows into columns
zip(*pairs) does the opposite: the * passes each pair as a separate argument, so the first items come out together and the second items together.
pairs = [("Ana", 31), ("Ben", 27), ("Chen", 45)]
names, ages = zip(*pairs)
print(names)
print(ages)
grid = [[1, 2, 3], [4, 5, 6]]
print(list(zip(*grid)))('Ana', 'Ben', 'Chen')
(31, 27, 45)
[(1, 4), (2, 5), (3, 6)]Common mistakes
Using the zip object twice
A zip object is used up after one pass. Turn it into a list if you need it again.
pairs = zip([1, 2], ["a", "b"])
print(list(pairs))
print(list(pairs))
pairs = list(zip([1, 2], ["a", "b"]))
print(len(pairs), pairs)[(1, 'a'), (2, 'b')] [] 2 [(1, 'a'), (2, 'b')]
Printing zip() directly
print(zip(a, b)) shows <zip object at 0x...>, not the pairs. Use print(list(zip(a, b))).
Questions people ask
How do I iterate over two lists at the same time in Python?
for a, b in zip(list1, list2):.
What if the lists have different lengths?
zip() stops at the shortest. Use strict=True (3.10+) to get an error instead, or itertools.zip_longest(a, b, fillvalue=None) to keep going.
How do I also get the index?
Combine with enumerate(): for i, (a, b) in enumerate(zip(x, y)):.
How do I unzip a list of pairs?
first, second = zip(*pairs). Both come back as tuples.