Sub topic 10
Unpacking in for loops: enumerate, zip and items
This chapter assumes you know basic Python syntax, lists and indexing, how to define and call functions, and how a plain for loop works. It also assumes you have seen basic unpacking, where x, y = 3, 4 assigns the items of a sequence to separate names.
The loop target is an assignment target
A for loop assigns each produced item to its target on every pass. The target does not have to be a single name. Any target that works on the left side of = works here, so each item is unpacked as it arrives.
Many built-in tools produce tuples. dict.items() yields (key, value) pairs, enumerate yields (index, item) pairs, and zip yields one tuple per position. Unpacking in the loop header lets you name those parts directly. The alternative is to index into a tuple with pair[0] and pair[1], which is harder to read.
Pairs from dict.items
prices = {"apple": 1.2, "pear": 0.8}
for item, price in prices.items():
print(item, price)Looping over a dictionary directly gives only its keys. Call .items() when you need both parts. Each pair is unpacked into item and price.
Counting with enumerate
enumerate wraps any iterable and yields (index, item) tuples. The start argument sets the first index, which is useful for numbering lines from 1.
names = ["Ada", "Linus", "Grace"]
for i, name in enumerate(names, start=1):
print(i, name)This replaces the older pattern of range(len(names)) followed by names[i].
Walking sequences together with zip
zip takes several iterables and yields a tuple holding one item from each, position by position. It stops when the shortest input runs out.
names = ["Ada", "Linus", "Grace"]
scores = [95, 88, 91]
for name, score in zip(names, scores):
print(name, score)Combining them: nested targets
You often want the index as well as the paired values. enumerate(zip(...)) yields (index, (name, score)), so the target mirrors that shape with parentheses around the inner pair.
names = ["Ada", "Linus", "Grace"]
scores = [95, 88, 91]
for i, (name, score) in enumerate(zip(names, scores), start=1):
print(i, name, score)The parentheses are required. Writing for i, name, score in enumerate(zip(...)) fails because each item has two parts, not three.
Starred targets in loops
Starred unpacking also works in a loop header. Each item is split the same way, and the starred name receives a list.
rows = [("a", 1, 2, 3), ("b", 4, 5)]
for label, *values in rows:
print(label, values)This prints a [1, 2, 3] and b [4, 5]. It is handy when rows have different lengths.
Common errors
- Wrong shape. If an item has a different number of parts than the target, Python raises
ValueError. Looping over[(1, 2, 3)]withfor a, b in ...gives "too many values to unpack (expected 2)". - Forgetting
.items().for k, v in prices:tries to unpack each key string. A two-letter key would unpack silently into two characters, and any other length raisesValueError. - Uneven zip.
zipdrops the extra items of the longer input without warning. In Python 3.10 and later,zip(a, b, strict=True)raisesValueErrorif the lengths differ. - Reusing the names. The loop names stay bound after the loop ends, and they overwrite any earlier variable with the same name.
Summary table
| Source | Each item looks like | Typical target |
|---|---|---|
| `d.items()` | `(key, value)` | `k, v` |
| `enumerate(seq)` | `(index, item)` | `i, x` |
| `zip(a, b)` | `(x, y)` | `x, y` |
| `enumerate(zip(a, b))` | `(i, (x, y))` | `i, (x, y)` |
Exercise
You have names = ["Ada", "Linus"] and scores = [95, 88]. Write a loop that prints each line as 1: Ada scored 95, with numbering starting at 1.
Show answer
for i, (name, score) in enumerate(zip(names, scores), start=1): print(f"{i}: {name} scored {score}")
Exercise
What happens with for k, v in {"ab": 1, "xyz": 2}:, and how do you fix it?
Show answer
The loop iterates over keys only. "ab" unpacks into k="ab"[0] and v="ab"[1], but "xyz" has three characters, so Python raises ValueError: too many values to unpack (expected 2). Fix it by looping over the dictionary's .items().