Sub topic 9
Looping over several iterables with zip()
This chapter assumes you can write a basic for loop, unpack a tuple into several names, and use enumerate(). It also assumes you know that a for loop works on any iterable. The strict=True option needs Python 3.10 or newer.
The problem zip() solves
You often have two lists that line up by position, such as names and scores. The index-based approach works but is noisy:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
for i in range(len(names)):
print(names[i], scores[i])zip() removes the indexing. It takes any number of iterables and yields one tuple per step. Each tuple holds the next item from every iterable.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
for name, score in zip(names, scores):
print(name, score)The loop target name, score unpacks each tuple. The loop is easier to read, and it also works for iterables that have no indexing, such as files, generators, and sets.
You can pass more than two iterables. The tuple then has one element per iterable:
cities = ["Oslo", "Lima", "Kyiv"]
temps = [4, 19, 7]
rain = [True, False, True]
for city, temp, wet in zip(cities, temps, rain):
print(f"{city}: {temp} C, rain={wet}")How zip() advances
On each step, zip() asks every input iterable for its next item. If all of them answer, it yields a tuple. If any one is exhausted, zip() stops.
Unequal lengths
By default, zip() stops at the shortest input and drops the leftover items without any warning:
a = [1, 2, 3]
b = ["x", "y"]
print(list(zip(a, b))) # [(1, 'x'), (2, 'y')]This is a common source of silent data loss. If a length mismatch means your data is wrong, say so with strict=True. It raises ValueError when the inputs differ in length:
try:
list(zip([1, 2, 3], "ab", strict=True))
except ValueError as e:
print(e) # zip() argument 2 is shorter than argument 1If a mismatch is expected and you want every item, use itertools.zip_longest(). It pads the shorter inputs with fillvalue, which defaults to None:
from itertools import zip_longest
print(list(zip_longest([1, 2, 3], ["x", "y"], fillvalue="-")))
# [(1, 'x'), (2, 'y'), (3, '-')]The next table helps you choose between the three behaviours.
| Situation | Tool |
|---|---|
| Extra items can be ignored | `zip(a, b)` |
| Different lengths indicate a bug | `zip(a, b, strict=True)` |
| You need every item from every input | `zip_longest(a, b, fillvalue=...)` |
zip() returns a one-shot iterator
zip() does not build a list. It returns a lazy iterator that produces tuples on demand, much as range computes numbers on demand. The difference is that a zip object can be consumed only once:
pairs = zip([1, 2], [3, 4])
print(list(pairs)) # [(1, 3), (2, 4)]
print(list(pairs)) # []The second list(pairs) is empty because the iterator is already used up. If you need to loop twice, call zip() again or store the result with list(). Do not call len() or index into a zip object, because neither is supported.
A subtle gotcha: input order and consumed iterators
zip() pulls from its inputs from left to right. If the first input still has items when a later one runs out, zip() has already taken one item from the first input and then discards it. With lists you will never notice. With iterators that you keep using afterwards, you will:
short = [10, 20]
a = iter([1, 2, 3])
print(list(zip(a, short))) # [(1, 10), (2, 20)]
print(list(a)) # [] (3 was pulled and lost)
b = iter([1, 2, 3])
print(list(zip(short, b))) # [(10, 1), (20, 2)]
print(list(b)) # [3]If you reuse an iterator after a zip(), put the one you want to keep intact last, or use strict=True so a mismatch fails loudly.
Common patterns
Combining with enumerate()
When you also need a counter, wrap the zip() in enumerate(). Put parentheses around the unpacked pair, because enumerate() yields (index, (a, b)):
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
for rank, (name, score) in enumerate(zip(names, scores), start=1):
print(rank, name, score)Comparing neighbouring items
Zipping a sequence with a shifted copy of itself gives you consecutive pairs. The result is as short as the shorter slice, so no index goes out of range:
nums = [3, 5, 9, 10]
diffs = [b - a for a, b in zip(nums, nums[1:])]
print(diffs) # [2, 4, 1]Building a dictionary
dict() accepts an iterable of pairs, so zip() is the standard way to join keys and values:
keys = ["name", "age", "city"]
values = ["Ada", 36, "London"]
record = dict(zip(keys, values))
print(record) # {'name': 'Ada', 'age': 36, 'city': 'London'}Unzipping and transposing
The * operator unpacks a list into separate arguments. Because zip(*pairs) receives each pair as its own argument, it reverses the pairing:
pairs = [(1, "a"), (2, "b"), (3, "c")]
nums, letters = zip(*pairs)
print(nums) # (1, 2, 3)
print(letters) # ('a', 'b', 'c')
rows = [[1, 2, 3], [4, 5, 6]]
print([list(col) for col in zip(*rows)]) # [[1, 4], [2, 5], [3, 6]]The same trick transposes a matrix, turning rows into columns. The results are tuples, so convert them with list() if you need lists.
Looping over a dictionary alongside a list
Iterating a dictionary yields its keys. Use .items() when you need pairs, and zip() when you are matching a dictionary's contents with a separate sequence:
prices = {"apple": 0.5, "pear": 0.75}
qty = [4, 2]
for (item, price), n in zip(prices.items(), qty):
print(item, price * n)This relies on dictionaries keeping insertion order, which is guaranteed from Python 3.7. Matching by position is fragile, so prefer looking up by key when you can.
Common errors
- Unpacking the wrong shape.
for a, b in zip(x, y, z)raisesValueError: too many values to unpack, because each tuple has three items. The number of names must equal the number of iterables. - Reusing a
zipobject. The second loop runs zero times and raises no error. Recreate it or store it withlist(). - Forgetting the silent truncation. Two lists that should match but don't will lose their tails. Use
strict=Truewhen equal length is part of your data's contract. - Reaching for
range(len(x))out of habit. If you only need the items, loop over them. If you need the index too, useenumerate(). Usezip()when several sequences must move together. - Modifying a list inside the loop. The caution from earlier chapters still applies.
zip()iterates over the lists live, so adding or removing items while looping can skip or repeat items.
Exercise
What does list(zip([1, 2, 3, 4], "ab")) return, and how would you change the call so that a length mismatch raises an error instead?
Show answer
It returns [(1, 'a'), (2, 'b')], because zip() stops at the shortest input and discards 3 and 4. Add strict=True: zip([1, 2, 3, 4], "ab", strict=True) raises ValueError (Python 3.10 or newer).
Exercise
Given months = ["Jan", "Feb", "Mar"] and sales = [120, 150, 90], write a loop that prints each month with its sales and a position number starting at 1, for example "1 Jan 120".
Show answer
for pos, (month, amount) in enumerate(zip(months, sales), start=1): print(pos, month, amount)
Exercise
A learner writes pairs = zip(a, b), then runs one loop over pairs, then a second loop over pairs. The second loop prints nothing. Why, and what are two fixes?
Show answer
A zip object is a one-shot iterator, so the first loop exhausts it. Fix it by calling zip(a, b) again for the second loop, or by storing the pairs with pairs = list(zip(a, b)) so they can be traversed repeatedly.