Sub topic 8
Using enumerate and zip together
This chapter assumes you can write a for loop over a list, unpack a tuple into several names, and use enumerate and zip on their own. Here you combine them to get a position and several parallel values in one loop.
The problem: a position plus parallel data
Suppose you have names and scores in two lists, and you want a numbered report. zip gives you the pairs. enumerate gives you the numbers. Each tool solves half of the problem, and you can stack them.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for i, (name, score) in enumerate(zip(names, scores), start=1):
print(f"{i}. {name}: {score}")This prints:
1. Ada: 95
2. Grace: 88
3. Linus: 91How the pieces nest
Evaluate the loop header from the inside out.
zip(names, scores)produces tuples such as("Ada", 95).enumerate(..., start=1)wraps each of those tuples in a new pair:(1, ("Ada", 95)).- The loop header
i, (name, score)has the same shape as that pair, so Python unpacks the outer tuple intoiand the inner tuple intonameandscore.
The parentheses in the loop header must mirror the nesting of the data. They are not decoration.
The most common error: flattening the pattern
It is tempting to write all three names at the same level. This fails, because enumerate still produces only two items per step: the counter and one tuple.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
try:
for i, name, score in enumerate(zip(names, scores)):
print(i, name, score)
except ValueError as error:
print(error)The message is not enough values to unpack (expected 3, got 2). The fix is to add the inner parentheses, as in i, (name, score).
Three or more sequences
The same idea extends to any number of inputs. The inner parentheses simply hold more names.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
cities = ["London", "New York", "Helsinki"]
for rank, (name, score, city) in enumerate(zip(names, scores, cities), start=1):
print(f"#{rank} {name} ({city}): {score}")Once the header becomes long, consider whether the loop is still readable. A common alternative is to keep the header short and unpack inside the body:
for rank, row in enumerate(zip(names, scores, cities), start=1):
name, score, city = row
print(f"#{rank} {name} ({city}): {score}")Both forms behave the same. Choose the one your teammates can read at a glance.
Order matters: enumerate outside, zip inside
You can also write zip(enumerate(a), b), but the result has a different shape: ((0, "Ada"), 95). It works, and the counter is tied to the first sequence only. In most code the counter describes the loop step, not one particular list, so enumerate(zip(...)) is the clearer choice.
Another option is to pass the counter to zip as its own sequence, using itertools.count:
from itertools import count
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for i, name, score in zip(count(1), names, scores):
print(i, name, score)This gives you a flat header with no nested parentheses. count(1) never ends, but zip stops at the shortest input, so the loop stops after three steps. The trade-off is that enumerate(zip(...)) is the form most Python readers expect, while zip(count(1), ...) needs a short comment for readers who have not seen it.
Unequal lengths still apply
enumerate adds no length rule of its own. Whatever zip does with mismatched inputs decides how many steps the loop runs. By default zip stops at the shortest input and drops the extras without any warning. If the lists should have equal length, pass strict=True (Python 3.10 and later), so a mismatch raises ValueError instead of silently losing data.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88]
try:
for i, (name, score) in enumerate(zip(names, scores, strict=True), start=1):
print(i, name, score)
except ValueError:
print("lengths differ")The loop prints the first two rows and then raises on the third step, because zip only discovers the mismatch when it runs out of one input. If your loop body has side effects, such as writing to a file, check the lengths before you start.
One-shot results
The object that enumerate(zip(...)) returns is an iterator, so you can loop over it once. If you need to loop twice, build a list first with rows = list(enumerate(zip(names, scores), start=1)), or call enumerate(zip(...)) again to create a fresh iterator.
Exercise
You have items = ["pen", "ink", "pad"] and prices = [1.5, 3.0, 2.25]. Write a loop that prints lines like 1. pen costs 1.5, numbering from 1. Then explain why for i, item, price in enumerate(zip(items, prices), start=1) fails.
Show answer
Use for i, (item, price) in enumerate(zip(items, prices), start=1): print(f"{i}. {item} costs {price}"). The zip call yields two-item tuples, and enumerate wraps each one with a counter, so each step has two top-level items: the counter and the tuple. A header with three flat names expects three top-level items and raises ValueError: not enough values to unpack (expected 3, got 2). The inner parentheses (item, price) are needed to unpack the nested tuple.