Built-in function

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.

BeginnerEvery example below runs in your browser. Change the code and press Run.

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

ParameterWhat it is
*iterables
required
Two or more things to loop over (one or none also work). Lists, tuples, strings, ranges, files…
strict
optional, 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

Pythoneditable
names = ["Lena", "Omar", "Yuki"]
scores = [88, 92, 79]
for name, score in zip(names, scores):
    print(f"{name}: {score}")
Output
Lena: 88
Omar: 92
Yuki: 79

2Build a dictionary from two lists

Pythoneditable
fields = ["name", "city", "age"]
values = ["Maria", "Lisbon", "34"]
person = dict(zip(fields, values))
print(person)
Output
{'name': 'Maria', 'city': 'Lisbon', 'age': '34'}

3Line totals from three lists

Pythoneditable
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}")
Output
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

Pythoneditable
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")
Output
[('Mon', 18), ('Tue', 21)]
ValueError: the lists have different lengths

Wed 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.

Pythoneditable
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)))
Output
('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.

Pythoneditable
pairs = zip([1, 2], ["a", "b"])
print(list(pairs))
print(list(pairs))
pairs = list(zip([1, 2], ["a", "b"]))
print(len(pairs), pairs)
Output
[(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.

Spotted a mistake on this page? Tell us