Sub topic 6
Looping over two or more sequences with zip
This chapter assumes you know basic Python syntax, for loops over lists, tuples and dictionaries, and how to call a function and use its return value. It builds on tuple unpacking in the loop header, which you have already seen with enumerate.
The problem: two lists that belong together
Data often arrives as parallel sequences. One list holds names and another holds scores, and position i in one matches position i in the other. The index-based way to walk them together looks like this:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for i in range(len(names)):
print(names[i], scores[i])This works, but it carries the same costs as range(len(seq)) elsewhere. You manage an index you do not care about, and nothing in the code says that the two lists are meant to be read side by side.
Pairing items with zip
zip takes two or more iterables and produces tuples. The first tuple holds the first item of each input, the second tuple holds the second item of each, and so on. Combined with tuple unpacking, each item gets a clear name:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for name, score in zip(names, scores):
print(f"{name}: {score}")The loop prints:
Ada: 95
Grace: 88
Linus: 91zip accepts any number of inputs. With three inputs, each tuple has three items, so the loop header needs three names. The number of names must match the number of inputs, or Python raises a ValueError.
What zip returns
zip(names, scores) does not build a list. It returns a zip object, which is an iterator. It produces one tuple at a time as the loop asks for the next one, so it uses very little memory even for large inputs. If you want to see the tuples at once, wrap it in list():
print(list(zip([1, 2, 3], ["a", "b", "c"])))
# [(1, 'a'), (2, 'b'), (3, 'c')]Because it is an iterator, a zip object can be consumed only once. A later chapter covers this pitfall in detail.
When the lengths differ
Real data does not always line up. By default, zip stops as soon as the shortest input runs out and silently drops the leftover items. You get no error and no warning.
from itertools import zip_longest
a = [1, 2, 3]
b = ["x", "y"]
print(list(zip(a, b)))
# [(1, 'x'), (2, 'y')]
print(list(zip_longest(a, b, fillvalue="-")))
# [(1, 'x'), (2, 'y'), (3, '-')]
try:
list(zip(a, b, strict=True))
except ValueError:
print("lengths differ")You have three options, and the right one depends on what a length mismatch means in your program.
| Option | Behavior with unequal lengths | Use it when |
|---|---|---|
| `zip(a, b)` | Stops at the shortest input | Extra items are safe to ignore |
| `zip(a, b, strict=True)` | Raises `ValueError` | A mismatch signals a bug. Requires Python 3.10+ |
| `itertools.zip_longest(a, b, fillvalue=...)` | Pads shorter inputs with the fill value | You need every item from every input |
With strict=True, the error is raised when the loop reaches the point where one input ends and another does not. Items before that point are still produced, so a loop may do some work before it fails.
Common mistakes
- Wrong number of names in the header. Zipping two lists and writing
for a, b, c in zip(x, y)fails with aValueErrorabout unpacking. - Assuming equal lengths. Without
strict=True, a short input quietly shortens the whole loop. - Reusing the zip object. After one full pass it is empty.
- Expecting a list. You cannot index a zip object (
zip(a, b)[0]raisesTypeError). Convert it withlist()first if you need that.
Practice
Exercise
What does list(zip([1, 2, 3, 4], ["a", "b"])) return, and how would you change the call so that it raises an error instead?
Show answer
It returns [(1, 'a'), (2, 'b')], because zip stops at the shortest input and drops 3 and 4. Add strict=True (Python 3.10+) as in zip([1, 2, 3, 4], ["a", "b"], strict=True) to raise ValueError when the lengths differ.
Exercise
Given names = ["Ada", "Grace"], roles = ["author", "admiral"] and years = [1843, 1952], write a loop that prints each name, role and year on one line.
Show answer
for name, role, year in zip(names, roles, years): print(name, role, year)