Sub topic 2
Unpacking tuples in the loop header
This chapter assumes you can write a for loop over a list, know what a tuple is, and can read basic dictionary code. Here you learn to unpack tuples directly in the for line. The later chapters on enumerate and zip rely on this skill.
What unpacking does
Tuple unpacking assigns the items of a tuple to separate names in one statement. The number of names on the left must match the number of items on the right.
point = (3, 7)
x, y = point
print(x)
print(y)This prints 3 and then 7. Without unpacking, you would write x = point[0] and y = point[1], which is longer and hides the meaning of each position.
Unpacking in a for loop
A for loop assigns each item from the iterable to the loop variable. If each item is a tuple, you can put several names in the loop header, and Python unpacks every tuple on every pass.
people = [("Ada", 36), ("Grace", 45), ("Linus", 28)]
for name, age in people:
print(f"{name} is {age}")On the first pass, the item is ("Ada", 36). Python then runs name, age = ("Ada", 36) for you. The loop body can use name and age instead of person[0] and person[1].
Compare the same loop without unpacking:
people = [("Ada", 36), ("Grace", 45), ("Linus", 28)]
for person in people:
print(f"{person[0]} is {person[1]}")The output is identical, but the reader has to remember what index 0 and index 1 mean.
Where tuples come from
Many built-in tools produce tuples, so you will use this pattern constantly. The items() method of a dictionary yields (key, value) pairs:
prices = {"apple": 0.5, "banana": 0.25, "cherry": 3.0}
for fruit, price in prices.items():
print(f"{fruit}: {price}")The functions enumerate and zip also yield tuples. That is why this chapter comes first.
Matching the shape
The names in the header must match the shape of each item. If they do not, Python raises a ValueError.
rows = [(1, "a", True), (2, "b", False)]
try:
for number, letter in rows:
print(number, letter)
except ValueError as error:
print(error)Each row has three items but the header has two names, so Python reports too many values to unpack (expected 2). If the header had more names than the tuple has items, the message would say not enough values to unpack.
Nested unpacking
An item can contain another tuple. Use parentheses in the header to mirror that structure.
records = [("Ada", (95, 88)), ("Grace", (72, 90))]
for name, (first, second) in records:
print(f"{name}: {first} and {second}")The outer tuple has two items: a name and an inner tuple. The parentheses tell Python to unpack the inner tuple as well. You will need this form when you combine enumerate and zip.
Collecting extra items with a starred name
A name with a * in front collects all the items that no other name received. It always becomes a list.
rows = [(1, "a", "b", "c"), (2, "d", "e")]
for number, *rest in rows:
print(number, rest)This prints 1 ['a', 'b', 'c'] and then 2 ['d', 'e']. Only one starred name is allowed in a single header.
Common errors
- Wrong count of names. The header must have as many names as the item has parts, unless you use a starred name.
- Forgetting the parentheses for nesting.
for name, first, second in recordsfails with the data above, because each item has two parts, not three. - Unpacking a string by accident. A string is also a sequence.
for a, b in ["xy", "zw"]works and givesa = "x"andb = "y", which can hide a mistake when you expected tuples. - Overwriting names. Loop variables are ordinary variables. After the loop ends,
nameandagestill hold the values from the last pass.
Summary table
| Header | Item it matches | Result |
|---|---|---|
| `for a, b in items` | `(1, 2)` | `a = 1`, `b = 2` |
| `for a, (b, c) in items` | `(1, (2, 3))` | `a = 1`, `b = 2`, `c = 3` |
| `for a, *rest in items` | `(1, 2, 3)` | `a = 1`, `rest = [2, 3]` |
| `for a, b in items` | `(1, 2, 3)` | `ValueError` |
Practice
Exercise
Given data = [("Ada", (95, 88)), ("Grace", (72, 90))], write a loop that prints each name with the sum of its two scores, for example Ada: 183. Use unpacking in the loop header.
Show answer
for name, (first, second) in data: print(f"{name}: {first + second}")
Exercise
What happens when you run for key, value, extra in {"a": 1}.items(): pass, and why?
Show answer
It raises ValueError: not enough values to unpack (expected 3, got 2). The items() method yields two-item tuples (key, value), but the header asks for three names.