Sub topic 9
Looping over several iterables with zip()
This chapter assumes you can write a basic for loop over a list, unpack a tuple into variables, and use enumerate(). It covers how zip() lets one loop walk through several iterables at the same time.
The problem zip() solves
Suppose you have two lists that line up by position: names and scores. A beginner's first attempt often loops over indexes.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
for i in range(len(names)):
print(names[i], scores[i])This works, but the index i is only a means to an end. zip() removes it.
Pairing items with zip()
zip() takes two or more iterables and produces tuples. The first tuple holds the first item of each iterable, the second tuple holds the second item of each, and so on. Unpacking the tuple in the for statement gives each item its own name.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
for name, score in zip(names, scores):
print(name, score)Output:
Ada 95
Grace 88
Linus 72zip() is lazy, like range(). It returns an iterator that builds each tuple only when the loop asks for it. Wrap it in list() to see all the pairs at once.
print(list(zip([1, 2, 3], "abc")))
# [(1, 'a'), (2, 'b'), (3, 'c')]You can pass any iterables, and they do not need the same type. You can also pass more than two.
for n, letter, flag in zip([1, 2], "xy", [True, False]):
print(n, letter, flag)Combining zip() with enumerate()
enumerate() wraps any iterable, including a zip() object. Each item is then a pair of the counter and the tuple from zip(), so the unpacking needs parentheses.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 72]
for rank, (name, score) in enumerate(zip(names, scores), start=1):
print(rank, name, score)Unequal lengths
By default, zip() stops when the shortest iterable runs out. It does not raise an error and it does not warn you.
for a, b in zip([1, 2, 3, 4], ["x", "y"]):
print(a, b)
# 1 x
# 2 yThe items 3 and 4 are silently dropped. If the lengths should match, a mismatch is a bug, and silence hides it. Since Python 3.10 you can pass strict=True, which raises ValueError when the lengths differ.
try:
for a, b in zip([1, 2, 3], ["x", "y"], strict=True):
print(a, b)
except ValueError as error:
print("Error:", error)If you want to keep every item and fill the gaps, use itertools.zip_longest().
from itertools import zip_longest
for a, b in zip_longest([1, 2, 3], ["x", "y"], fillvalue="-"):
print(a, b)
# 1 x
# 2 y
# 3 -One-shot iterators
A zip object is an iterator, so you can loop over it only once. A second loop over the same object finds it empty.
pairs = zip([1, 2], [3, 4])
print(list(pairs)) # [(1, 3), (2, 4)]
print(list(pairs)) # []If you need the pairs more than once, store them with list(zip(...)).
Unzipping
Placing * before an argument spreads a sequence into separate arguments. Applied to a list of pairs, zip(*pairs) reverses the pairing.
pairs = [(1, "a"), (2, "b"), (3, "c")]
numbers, letters = zip(*pairs)
print(numbers) # (1, 2, 3)
print(letters) # ('a', 'b', 'c')Summary
zip(a, b)yields tuples that hold the items at the same position.- Unpack the tuples in the
forheader:for x, y in zip(a, b). - It stops at the shortest input unless you use
strict=Trueorzip_longest(). - A
zipobject can be consumed only once.
Exercise
What does this code print, and why? for a, b in zip([1, 2, 3], "ab"): print(a, b)
Show answer
It prints "1 a" and "2 b". zip() stops when the shortest iterable, the string "ab", is exhausted, so the item 3 is never used and no error is raised. Adding strict=True (Python 3.10+) would make it raise ValueError instead.
Exercise
Given keys = ["a", "b", "c"] and values = [1, 2, 3], write a loop using zip() that prints each key and value, and explain why you cannot loop over the same zip object twice.
Show answer
for key, value in zip(keys, values): print(key, value). A zip object is an iterator, and an iterator is used up once the loop has taken all its items. A second loop would get nothing, so store list(zip(keys, values)) if you need to reuse the pairs.