Sub topic 6
Looping over two or more sequences with zip
This chapter covers zip when you give it equal-length inputs, which is the normal case. It assumes you can write a for loop over a list and unpack a tuple in a loop header, such as for key, value in pairs. It also assumes you know the difference between an iterable and an iterator, and you can call a function and use its return value. Unequal lengths, strict=True and zip_longest get their own chapter. Combining zip with enumerate, building dictionaries, and one-shot iterators are also covered later. Here the goal is a working model of what zip does and where it goes wrong.
The problem zip solves
Data often arrives as parallel sequences. Position 0 of one list belongs with position 0 of another, and so on. Two lists of names and scores are a typical case.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for i in range(len(names)):
print(names[i], scores[i])This works, but the loop introduces an index i that you never wanted. You have to remember that scores is at least as long as names. Both sequences also have to support indexing. A generator, a file object, or a map result cannot be indexed, so this pattern fails on them.
zip removes the index:
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for name, score in zip(names, scores):
print(f"{name}: {score}")Output:
Ada: 95
Grace: 88
Linus: 91Each pass through the loop gets one item from each input, and each item has its own name.
How zip pairs items
zip(a, b) walks both inputs in step. On the first step it takes the first item of a and the first item of b and bundles them into a tuple. On the second step it does the same with the second items. It stops when any input runs out.
The tuples are the values the loop receives. The loop header for name, score in ... unpacks each tuple into two variables, the same way a, b = (1, 2) does.
What zip returns
zip is a class, and calling it builds a zip object. That object is an iterator. It does not hold the pairs. It holds iterators over your inputs and builds each tuple only when asked.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
pairs = zip(names, scores)
print(type(pairs))
# <class 'zip'>
print(next(pairs))
# ('Ada', 95)
print(next(pairs))
# ('Grace', 88)
print(list(pairs))
# [('Linus', 91)]Three consequences follow from this.
- Memory stays flat. Zipping two lists of ten million items does not create ten million tuples up front. Only the current tuple exists at any time.
- You can't index or measure it.
pairs[0]andlen(pairs)both raiseTypeError. Wrap it inlist(...)if you need either, and accept the memory cost. - It is consumed as you go. The
list(pairs)call above returned only the remaining pair, because two items had already been taken withnext. The pitfalls chapter covers this in detail. For now, treat azipobject as something you loop over once.
Unpacking in the loop header
The loop variable can be a single name or an unpacking pattern. Both are valid, and they do different things.
names = ["Ada", "Grace"]
scores = [95, 88]
for pair in zip(names, scores):
print(pair, pair[0], pair[1])
for name, score in zip(names, scores):
print(name, score)Output:
('Ada', 95) Ada 95
('Grace', 88) Grace 88
Ada 95
Grace 88With one name, you get the whole tuple and must index into it. With several names, Python unpacks the tuple for you. Prefer unpacking, because name and score explain themselves in a way that pair[0] and pair[1] don't.
The number of names must match the number of inputs. If it doesn't, Python raises a ValueError at the first iteration:
a = [1, 2]
b = [3, 4]
c = [5, 6]
try:
for x, y in zip(a, b, c):
print(x, y)
except ValueError as error:
print(error)
# too many values to unpack (expected 2)The message mentions unpacking, not zip, so it can be confusing. When you see "too many values" or "not enough values" in a zip loop, count the inputs and count the names.
Three or more sequences
zip accepts any number of inputs. Each tuple has one item per input.
products = ["pen", "notebook", "stapler"]
prices = [1.50, 3.25, 8.00]
quantities = [10, 4, 2]
for product, price, qty in zip(products, prices, quantities):
print(f"{product}: {price * qty:.2f}")Output:
pen: 15.00
notebook: 13.00
stapler: 16.00The order of the inputs sets the order inside each tuple and the order of the names in the header. Keep the two in the same order. If you swap two names, the code still runs and silently multiplies the wrong things.
Past four or five inputs, the header gets hard to read. That is a sign that the data should be a list of records, such as dictionaries or dataclass instances, instead of many parallel lists.
Any iterable works
zip needs only iterables, not lists. You can mix types freely:
for letter, number in zip("abc", range(1, 4)):
print(letter, number)Output:
a 1
b 2
c 3Here is how common iterable types behave as zip inputs.
| Input type | What `zip` takes from it |
|---|---|
| `list`, `tuple` | Items in order |
| `str` | One character at a time |
| `range` | Each integer in the range |
| `dict` | Keys, in insertion order. Use `.values()` or `.items()` for the others |
| `set` | Items in an arbitrary order, so avoid pairing a set with ordered data |
| file object | One line at a time, including the trailing newline |
| generator | Each yielded value, produced on demand |
Because range and generators are fine inputs, zip is also a clean way to pair data with a computed sequence. It never needs the second input to exist as a list in memory.
def squares():
n = 1
while True:
yield n * n
n += 1
for label, square in zip(["a", "b", "c"], squares()):
print(label, square)Output:
a 1
b 4
c 9The generator squares() never ends on its own. The loop still terminates, because zip stops when the three-item list runs out.
Reading two positions of the same sequence
You can pass the same sequence more than once, or pass slices of it. A common use is comparing each item with the one after it:
temps = [18, 21, 19, 25]
for before, after in zip(temps, temps[1:]):
print(f"{before} -> {after}: change {after - before}")Output:
18 -> 21: change 3
21 -> 19: change -2
19 -> 25: change 6The slice temps[1:] is one item shorter, so zip stops after three pairs. There is no index to keep within bounds, and no off-by-one error at the last item. This is a case where stopping at the shortest input is exactly what you want.
Slicing copies the list, which is fine for small data. For a large sequence, itertools.islice gives the same view without a copy.
Building results with zip
Loops that compute a value for each pair often read better as comprehensions or as calls to sum:
prices = [1.50, 3.25, 8.00]
quantities = [10, 4, 2]
line_totals = [price * qty for price, qty in zip(prices, quantities)]
print(line_totals)
# [15.0, 13.0, 16.0]
print(sum(price * qty for price, qty in zip(prices, quantities)))
# 44.0Note the second form. A generator expression inside sum never builds the intermediate list, and zip itself is lazy, so the whole pipeline processes one pair at a time.
A related mistake is trying to update a list through the loop variables:
scores = [95, 88, 91]
bonus = [2, 2, 2]
for score, extra in zip(scores, bonus):
score = score + extra # rebinds the local name only
print(scores)
# [95, 88, 91]The assignment changes the loop variable score, not the list. To get new values, build a new list:
scores = [score + extra for score, extra in zip(scores, bonus)]
print(scores)
# [97, 90, 93]If other code holds a reference to the original list and must see the change, assign to a slice instead: scores[:] = [...].
Edge cases
Two special inputs behave in ways that are logical but easy to trip over.
print(list(zip([1, 2, 3])))
# [(1,), (2,), (3,)]
print(list(zip()))
# []With one input, zip produces one-item tuples. With no inputs, it produces nothing, so a loop over zip() runs zero times and raises no error.
The zero-input case matters when you call zip(*lists) and lists might be empty. The loop is skipped silently. A later chapter returns to zip(*...) for unzipping data.
Empty inputs behave the same way. If any input is empty, the whole zip is empty:
print(list(zip(["a", "b"], [])))
# []A loop that "does nothing" because one list was accidentally empty is a quiet failure. If an empty result would be a bug in your program, check for it explicitly before the loop.
A preview of stopping early
By default, zip stops at the shortest input and says nothing about the leftovers:
print(list(zip([1, 2, 3], ["x", "y"])))
# [(1, 'x'), (2, 'y')]The 3 is dropped without a warning. The next chapter covers strict=True and itertools.zip_longest as the ways to catch or pad this case.
There is one more consequence you should know about now. It matters when an input is an iterator that you keep using afterwards. zip asks its inputs for items from left to right on each step. If the first input has an item but a later one is exhausted, the item from the first input has already been taken and is lost:
it = iter([1, 2, 3])
short = ["a"]
print(list(zip(it, short)))
# [(1, 'a')]
print(next(it))
# 3The value 2 was pulled from it, then zip found that short had nothing left and stopped. The 2 was never delivered to anyone. If you swap the argument order, zip(short, it), the exhausted input is checked first and it is not advanced, so next(it) would return 2. Order rarely matters for lists, but it matters when you keep using an iterator after the zip ends.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Names in the header don't match the number of inputs | `ValueError: too many values to unpack` or `not enough values to unpack` | Count inputs and names |
| Calling `len()` or indexing a `zip` object | `TypeError` | Wrap it in `list(...)` if you need that |
| Assuming the inputs have equal length | Items silently missing from the output | Check lengths, or use `strict=True` (next chapter) |
| Assigning to the loop variable to modify a list | The list is unchanged | Build a new list, or assign to a slice |
| Zipping a set with ordered data | Pairings differ between runs | Convert to a sorted list first |
| Reusing the same `zip` object | Second loop runs zero times | Call `zip(...)` again to get a fresh iterator |
Checking your model
The following short program uses everything above. Predict its output before you run it.
labels = ["low", "mid", "high"]
limits = [10, 50, 100]
counts = [3, 0, 7]
for label, limit, count in zip(labels, limits, counts):
status = "empty" if count == 0 else f"{count} items"
print(f"{label} (<= {limit}): {status}")
print(list(zip(labels, counts))[1:])Output:
low (<= 10): 3 items
mid (<= 50): empty
high (<= 100): 7 items
[('mid', 0), ('high', 7)]The last line shows the pattern from earlier. You can't slice the zip object directly, but you can slice the list you get from it.
Exercise
A loop for city, temp in zip(cities, temps, humidity): raises ValueError: too many values to unpack (expected 2). Why does it fail, and what are two ways to fix it?
Show answer
zip is given three inputs, so each tuple has three items, but the header has only two names. One fix is to add a third name: for city, temp, hum in zip(cities, temps, humidity):. The other is to remove humidity from the zip call if the loop doesn't need it.
Exercise
Given prices = [4.0, 5.5, 6.0] and discounts = [0.5, 1.0, 0.0], write one expression that produces the list of discounted prices [3.5, 4.5, 6.0] without using an index. Then explain why for p, d in zip(prices, discounts): p = p - d would not change prices.
Show answer
Use [p - d for p, d in zip(prices, discounts)]. In the loop, p = p - d rebinds the local name p to a new number. It does not write into the list, so prices stays the same. You must build a new list or assign into the list by position.
Exercise
Write a loop that prints the difference between each reading and the next in readings = [10, 14, 9, 20], using zip and a slice. What does it print, and how many lines?
Show answer
for a, b in zip(readings, readings[1:]): print(b - a). It prints 4, -5 and 11, which is three lines. The slice is one item shorter than the list, so zip stops after three pairs.