Sub topic 10
Unpacking in for loops: enumerate, zip and items
This chapter shows how a for loop can unpack each item into several names. It then applies that to the three most common sources of paired data: enumerate, zip and dict.items. It assumes you can write a basic for loop and have read the earlier chapters on packing, unpacking and nested unpacking.
The loop target is an assignment target
A for loop does not only accept a single name. The part between for and in is an assignment target, and Python assigns to it once per iteration. Any target that works on the left side of = also works there, including a tuple of names, a starred name, or a nested pattern.
pairs = [(1, "one"), (2, "two"), (3, "three")]
for number, word in pairs:
print(number, word)Each iteration produces one tuple, such as (1, "one"). Python then runs the equivalent of number, word = (1, "one"). The loop body sees two names and never sees the tuple.
The dotted path matters. If an item has the wrong number of parts, the error is raised at the for line on that iteration. Earlier iterations have already run their bodies.
enumerate: index and item
enumerate(iterable) yields (index, item) tuples. The unpacking form replaces the older pattern of range(len(items)) plus indexing.
colors = ["red", "green", "blue"]
for i, color in enumerate(colors):
print(i, color)
for i, color in enumerate(colors, start=1):
print(f"{i}. {color}")The first loop prints 0 red, 1 green and 2 blue. The start argument changes only the number. It does not skip any items. Use start=1 for numbered output shown to people.
enumerate works on any iterable, including files, generators and strings. It does not need len() or random access.
zip: walking several sequences together
zip(a, b, ...) yields one tuple per position, holding the items at that position from each input.
names = ["Ada", "Linus", "Grace"]
scores = [95, 88, 91]
for name, score in zip(names, scores):
print(f"{name}: {score}")You can zip more than two inputs. The target then needs one name per input.
cities = ["Oslo", "Lima", "Kyoto"]
temps = [4, 19, 12]
countries = ["Norway", "Peru", "Japan"]
for city, temp, country in zip(cities, temps, countries):
print(city, country, temp)Unequal lengths
By default zip stops silently at the end of the shortest input. That behaviour often hides bugs.
names = ["Ada", "Linus", "Grace"]
scores = [95, 88]
print(list(zip(names, scores)))
try:
list(zip(names, scores, strict=True))
except ValueError as e:
print(e)The first print shows only two pairs, so Grace has disappeared with no warning. With strict=True (Python 3.10 and later), the mismatch raises ValueError: zip() argument 2 is shorter than argument 1. Use strict=True when the inputs are supposed to line up. When you want to keep the longer input, use itertools.zip_longest.
from itertools import zip_longest
names = ["Ada", "Linus", "Grace"]
scores = [95, 88]
for name, score in zip_longest(names, scores, fillvalue=0):
print(name, score)Unzipping with `*`
zip is its own inverse when combined with * argument unpacking. This turns a list of pairs into separate sequences.
pairs = [("a", 1), ("b", 2), ("c", 3)]
letters, numbers = zip(*pairs)
print(letters)
print(numbers)The result is two tuples: ('a', 'b', 'c') and (1, 2, 3). If pairs is empty, zip(*pairs) yields nothing and the assignment raises ValueError, because there is nothing to unpack into two names.
dict.items: keys and values
Looping over a dictionary directly gives only the keys. The items() view yields (key, value) tuples.
prices = {"apple": 1.2, "pear": 0.8, "plum": 2.5}
for item, price in prices.items():
print(f"{item} costs {price}")
for item in prices:
print(item)The second loop prints keys only. The sibling views keys() and values() give one thing per iteration, so they need no unpacking.
Dictionaries keep insertion order, so the loop visits entries in the order they were added. To visit them in another order, wrap the view in sorted.
prices = {"apple": 1.2, "pear": 0.8, "plum": 2.5}
for item, price in sorted(prices.items()):
print(item, price)
for item, price in sorted(prices.items(), key=lambda kv: kv[1]):
print(item, price)The first loop sorts by key, because tuples compare element by element. The second sorts by price. The lambda receives the whole tuple as one argument, so you index it with kv[1]. A lambda cannot unpack in its parameter list in Python 3.
Changing a dictionary while looping
Adding or removing keys during iteration raises RuntimeError: dictionary changed size during iteration. Loop over a snapshot instead.
prices = {"apple": 1.2, "pear": 0.8, "plum": 2.5}
for item, price in list(prices.items()):
if price < 1:
del prices[item]
print(prices)Changing the value of an existing key during the loop is allowed, because the size does not change.
Combining the forms
The target pattern must mirror the shape of what the iterable yields. Wrapping one iterator in another produces nested tuples, so you use a nested target with parentheses.
names = ["Ada", "Linus", "Grace"]
scores = [95, 88, 91]
for i, (name, score) in enumerate(zip(names, scores), start=1):
print(i, name, score)zip yields (name, score). enumerate wraps that in (i, (name, score)). The parentheses in the target are required, because without them the target has three names and each item has two parts.
names = ["Ada", "Linus", "Grace"]
scores = [95, 88, 91]
try:
for i, name, score in enumerate(zip(names, scores)):
print(i, name, score)
except ValueError as e:
print(e)This prints not enough values to unpack (expected 3, got 2). The same idea applies to enumerate(d.items()), which needs the target i, (key, value).
| Iterable | Each item looks like | Target |
|---|---|---|
| `enumerate(xs)` | `(0, x)` | `i, x` |
| `zip(xs, ys)` | `(x, y)` | `x, y` |
| `d.items()` | `(key, value)` | `k, v` |
| `enumerate(zip(xs, ys))` | `(0, (x, y))` | `i, (x, y)` |
| `enumerate(d.items())` | `(0, (key, value))` | `i, (k, v)` |
Starred targets in loops
A starred name collects the leftover parts of each item into a list. This helps when items have different lengths.
rows = [
("Ada", 95, 90, 100),
("Linus", 70, 80),
]
for name, *marks in rows:
print(name, sum(marks) / len(marks))This prints Ada 95.0 and Linus 75.0. The star can sit anywhere, but only one starred name is allowed per target. A starred target collects zero or more items, so marks can be an empty list. In that case the division in the example would raise ZeroDivisionError, which is a different bug from an unpacking error.
Pitfalls
Strings unpack silently
A string is an iterable of characters, so a two-character string unpacks into two names without complaint.
for a, b in ["xy", "zw"]:
print(a, b)This works and prints x y and z w. Now suppose you meant to loop over a dictionary but left out .items().
codes = {"ab": 1, "cd": 2}
for key, value in codes:
print(key, value)Here the keys are two-character strings, so the loop runs and prints a b and c d. The values are never touched. With keys of any other length, you get ValueError instead. If a loop unpacks keys that are strings, check that you did not forget .items().
Length mismatches
The same errors as in plain unpacking apply, but they appear mid-loop.
too many values to unpack (expected 2)means an item has more parts than your target has names.not enough values to unpack (expected 3, got 2)means an item has fewer parts.cannot unpack non-iterable int objectmeans the item is not a sequence at all. For example, you wrotefor a, b in [1, 2, 3].
When data comes from outside your program, a starred target or a length check is safer than hoping every row has the same shape.
One-shot iterators
zip, enumerate and dict.items() results behave differently when reused. A zip or enumerate object is an iterator, so a second loop over it sees nothing.
pairs = zip([1, 2], ["a", "b"])
print(list(pairs))
print(list(pairs))The second print shows []. Call zip again, or store list(zip(...)) if you need several passes. A dict.items() view can be reused, because it is a view and not an iterator.
Loop names outlive the loop
The target names are ordinary variables in the surrounding scope. After the loop ends, i and name still hold the values from the last iteration. If the iterable is empty, they are never assigned, and using them later raises NameError (or silently reuses an older value of the same name). Avoid reusing a loop name for something unrelated later in the same function.
Choosing a form
- Use
enumeratewhen you need the position. Do not keep a manual counter. - Use
zipfor parallel sequences, and addstrict=Truewhen equal length is part of the contract. - Use
.items()whenever you need both the key and the value. - Give each target name a meaning (
name,score), notxandy. A good name often removes the need for a comment. - When a record has more than three or four fields, prefer a named tuple or a dataclass over a long positional target. Named tuples are covered in a later chapter.
Exercise
What does this code print, and why?
data = {"a": 1, "b": 2}
for i, (k, v) in enumerate(data.items()):
print(i, k, v)
Then explain what happens if you change the loop header to for i, k, v in enumerate(data.items()):.
Show answer
The first version prints "0 a 1" and "1 b 2". data.items() yields (key, value) pairs, and enumerate wraps each pair as (index, (key, value)), which the nested target i, (k, v) matches. The second header raises ValueError: not enough values to unpack (expected 3, got 2) on the first iteration, because each item has only two parts: the index and the pair. The parentheses are what tell Python to unpack the inner pair.
Exercise
You have keys = ["x", "y", "z"] and values = [10, 20]. Write a loop that prints each key with its value and fails loudly instead of dropping "z". Then write a version that prints z 0 for the missing value.
Show answer
Strict version (Python 3.10+): for k, v in zip(keys, values, strict=True): print(k, v). It prints "x 10" and "y 20", then raises ValueError: zip() argument 2 is shorter than argument 1 when it reaches the third key. Padded version: from itertools import zip_longest and then for k, v in zip_longest(keys, values, fillvalue=0): print(k, v). It prints "x 10", "y 20" and "z 0".