Sub topic 2
Unpacking tuples in the loop header
This chapter assumes you can write a for loop over a list, you know that a tuple is an ordered, fixed-size group of values, and you have used dictionaries. It does not assume you have used enumerate or zip yet. The point of this chapter is the loop header itself, the part between for and in. Every later chapter relies on it.
Why the loop header matters
Look at these two loops:
pairs = [("Ada", 95), ("Grace", 88), ("Linus", 91)]
for pair in pairs:
print(pair[0], "scored", pair[1])
for name, score in pairs:
print(name, "scored", score)Both print the same three lines. The second loop gives each part of the pair its own name, so you do not have to remember that pair[1] means the score. The mechanism is called tuple unpacking (also called destructuring). Python splits one value into several names in a single step.
enumerate and zip both produce tuples. Once you read for index, value in enumerate(items) as plain unpacking, there is nothing special left to learn about its syntax.
Unpacking in plain assignment
A for loop header uses the same rules as an assignment statement, so start there.
point = (3, 4)
x, y = point
print(x, y) # 3 4
a, b = 1, 2
a, b = b, a # swap without a temporary variable
print(a, b) # 2 1The right-hand side is evaluated first. Python then walks through it and assigns the first item to the first name, the second item to the second name, and so on. The right-hand side in a, b = b, a is itself a tuple, (b, a), built before any assignment happens. That is why the swap works.
Three facts carry over to loops:
- The right-hand side can be any iterable, not only a tuple. Lists, strings, dictionary views, and iterators such as
enumerateobjects all work. - The number of names must match the number of items, unless you use a starred name (covered below).
- Parentheses around the names are optional.
x, y = pointand(x, y) = pointmean the same thing.
What the loop does on each pass
A for loop asks the iterable for its next item, assigns that item to the target in the header, and runs the body. Then it repeats. When the target is name, score, the assignment on each pass is name, score = item.
The unpacking happens once per pass, before the body runs. If it fails, the error comes from the for line, not from inside the body.
Unpacking in the header
Here is the pattern with a list of tuples, which is the most common case:
pairs = [("Ada", 95), ("Grace", 88), ("Linus", 91)]
for name, score in pairs:
print(f"{name}: {score}")The parenthesized form for (name, score) in pairs: is equivalent. Most style guides prefer the version without parentheses.
You can see what enumerate hands to the loop by turning it into a list:
print(list(enumerate(["a", "b"])))
# [(0, 'a'), (1, 'b')]Each item is a two-element tuple, so for index, letter in enumerate(...) unpacks exactly as for name, score in pairs does.
Dictionaries
Looping over a dictionary directly gives only its keys. The items() method gives (key, value) tuples, which you unpack:
prices = {"apple": 0.5, "pear": 0.75}
for fruit, price in prices.items():
print(fruit, price)Two sibling methods work the same way without unpacking: prices.keys() and prices.values() each yield single items.
Unpacking works on any iterable of the right size
The items do not have to be tuples. Lists, strings, and ranges unpack too, as long as the count matches:
for first, second in [[1, 2], "ab", range(5, 7)]:
print(first, second)
# 1 2
# a b
# 5 6This flexibility is useful, and it also causes one of the gotchas covered later in this chapter.
Nested unpacking
When an item contains another tuple, mirror its shape in the header with parentheses:
students = [
("Ada", (95, 88)),
("Grace", (88, 92)),
]
for name, (midterm, final) in students:
average = (midterm + final) / 2
print(f"{name}: {average}")
# Ada: 91.5
# Grace: 90.0Here the parentheses are required. Without them, name, midterm, final would describe a three-item shape, and each student has only two items.
The same idea applies to dictionaries whose values are tuples:
coords = {"Oslo": (59.91, 10.75), "Lima": (-12.05, -77.04)}
for city, (lat, lon) in coords.items():
print(f"{city}: {lat}, {lon}")The header reads left to right as a description of the data: a key, then a pair. The header must match the shape of each item. The chapter on combining enumerate and zip applies this rule to i, (name, score).
Ignoring values with an underscore
If you need only some of the parts, use _ for the ones you do not want. It is an ordinary variable name, but by convention it signals "not used".
pairs = [("Ada", 95), ("Grace", 88), ("Linus", 91)]
for _, score in pairs:
print(score)
for name, _ in pairs:
print(name)You can use _ more than once in the same header, as in for _, _, z in triples. Do not use _ if your code also uses it for something else in the same scope. Some tools, such as translation functions in some frameworks, also bind _.
Starred names collect the rest
When items vary in length, or you want the first or last element and everything else, prefix one name with *. That name receives a list of all the items that no other name claimed.
rows = [(1, 2, 3), (4, 5), (6,)]
for first, *rest in rows:
print(first, rest)
# 1 [2, 3]
# 4 [5]
# 6 []
for *head, last in rows:
print(head, last)
# [1, 2] 3
# [4] 5
# [] 6Points to remember:
- The starred name always receives a list, even if the source was a tuple. It is an empty list when nothing is left over.
- At most one starred name is allowed per level of the header.
a, *b, *cis a syntax error. - Each non-starred name still needs a value, so
for first, second, *rest in rowsfails on the row(6,).
The header patterns at a glance
| Header | Matches items shaped like | Example item |
|---|---|---|
| `for x in` | one value of any kind | `"apple"` |
| `for a, b in` | exactly two values | `("Ada", 95)` |
| `for a, (b, c) in` | a value, then a pair | `("Ada", (95, 88))` |
| `for a, *rest in` | one or more values | `(1, 2, 3)` |
| `for *init, last in` | one or more values | `(1, 2, 3)` |
| `for _, b in` | exactly two, first ignored | `("Ada", 95)` |
Common errors
Wrong number of values
If the item has a different number of values than the header has names, Python raises ValueError on the for line. The message tells you the expected count and, when there are too few, the actual count.
rows = [("Ada", 95), ("Grace",), ("Linus", 91, "late")]
for row in rows:
try:
name, score = row
except ValueError as error:
print(row, "->", error)
# ('Grace',) -> not enough values to unpack (expected 2, got 1)
# ('Linus', 91, 'late') -> too many values to unpack (expected 2)The try block here reproduces the loop's assignment so that the demo can continue past each failure. In a real loop you would normally fix the data or the header instead of catching the error.
A very common version of this mistake comes from adding zip inside enumerate:
names = ["Ada", "Grace"]
scores = [95, 88]
# Wrong: enumerate yields (index, (name, score)), which is two items, not three
# for i, name, score in enumerate(zip(names, scores)):
# Right: mirror the nesting
for i, (name, score) in enumerate(zip(names, scores)):
print(i, name, score)The wrong version raises ValueError: not enough values to unpack (expected 3, got 2). When you see that message, compare the shape of the header with the shape of one item.
Forgetting `.items()`
prices = {"apple": 0.5, "pear": 0.75}
# for fruit, price in prices: # ValueError: too many values to unpack (expected 2)Looping over prices yields the strings "apple" and "pear". Python tries to split "apple" into two names, finds five characters, and fails.
The silent mistake
The same mistake with two-character keys does not fail. It gives wrong results instead:
codes = {"ab": 1, "cd": 2}
for key, value in codes:
print(key, value)
# a b
# c dEach key is a two-character string, so it unpacks into two single characters. No error is raised, and value is not the dictionary's value at all. Always write codes.items() when you want both parts. This is the main reason to treat unpacking as a shape check you should think about, not only as convenient syntax.
The names outlive the loop
Names in a loop header are ordinary variables in the enclosing scope. They keep their last value after the loop ends:
pairs = [("Ada", 95), ("Grace", 88), ("Linus", 91)]
for name, score in pairs:
pass
print(name, score) # Linus 91If the iterable is empty, the loop never assigns anything, and using the names afterward raises NameError. Two practical consequences follow:
- Do not rely on a loop variable after the loop unless you are sure the loop ran at least once.
- A loop header can overwrite a variable you already had. If
nameheld something useful before the loop, it is gone afterward. Pick header names that do not collide with existing ones.
List, set, and dictionary comprehensions are different. They have their own scope, so their loop names do not leak out:
labels = [f"{name}={score}" for name, score in pairs]
print(labels) # ['Ada=95', 'Grace=88', 'Linus=91']The unpacking syntax in a comprehension is the same as in a for statement.
Choosing names that read well
Unpacking pays off only if the names help. A few guidelines:
- Use names that describe the data, such as
name, score, nota, borx, y, unless the data really is coordinates. - Keep the header short. If it needs three levels of parentheses, unpack in two steps or restructure the data.
- Prefer
for index, item in enumerate(items)over a single name plus indexing. It tells the reader what each part means. - If you use only one part of each item, use
_for the rest, or loop over a single sequence directly.
When the shape is unclear, a plain assignment inside the body can help:
for record in records:
name, (midterm, final) = record
...That is the same unpacking, written on its own line. It gives you a normal traceback line if the shape is wrong, and it lets you keep record around if you need the whole item.
Exercises
Exercise
What does this loop print, and why? pairs = [("a", 1), ("b", 2)] for letter, number in pairs: print(number, letter)
Show answer
It prints "1 a" and then "2 b". Each tuple is unpacked into letter and number on every pass. The print call lists number first, so the order of the output is reversed from the tuple order.
Exercise
The loop below raises ValueError. Explain why, and fix it so it prints each fruit and its price. prices = {"apple": 0.5, "pear": 0.75} for fruit, price in prices: print(fruit, price)
Show answer
Looping over a dictionary yields only its keys, so Python tries to unpack the string "apple" into two names and finds five characters (expected 2). The fix is to loop over prices.items(), which yields (key, value) tuples: for fruit, price in prices.items().
Exercise
Given records = [("Ada", (95, 88)), ("Grace", (88, 92))], write a loop header that gives you name, midterm, and final as three separate names, and print the highest of the two scores for each person.
Show answer
for name, (midterm, final) in records: print(name, max(midterm, final)) The parentheses mirror the nested tuple. The output is "Ada 95" and "Grace 92".
Exercise
Given rows = [(1, 2, 3, 4), (5, 6), (7,)], what does "for first, rest in rows: print(first, rest)" print? What changes if you write "for first, second, rest in rows" instead?
Show answer
The first loop prints "1 [2, 3, 4]", "5 [6]", and "7 []". The starred name always gets a list, empty if nothing is left. With "first, second, *rest", the first two rows work, but the row (7,) has only one value for two required names, so it raises ValueError: not enough values to unpack (expected at least 2, got 1).
Exercise
Why does "for key, value in {'ab': 1, 'cd': 2}:" run without an error, and what does it assign to key and value?
Show answer
Each key is a two-character string, and a string is an iterable, so it unpacks into two single characters. The first pass assigns key = "a" and value = "b", and the second assigns key = "c" and value = "d". The dictionary's real values (1 and 2) are never used. The correct form is to loop over .items().