Unpacking
🌍 In real life. A teacher hands back a pile of three exam papers to three students standing in a row: the first paper to the first student, the second to the second, the third to the third. One movement, everyone gets theirs. If there are four papers and three students, something's wrong.
Unpacking hands out the items of a tuple or list the same way.
The idea in one sentence: unpacking gives the items of a tuple or list to several names at once, in order, one name for each item.
Its words:
- unpacking:
x, y = pointputspoint[0]in x andpoint[1]in y - packing:
1, 2on the right of=makes a tuple first - starred name:
*restcollects all the leftover items into a list
Step by step, for x, y = 3, 4:
- The right side is packed into a tuple:
(3, 4). - Python counts: 2 names, 2 items. They match.
- The first item goes to x, the second to y.
point = (3, 4)
x, y = point
print(x, y)
a, b = 1, 2
a, b = b, a
print(a, b)If the numbers don't match, Python stops with a ValueError:
x, y = (1, 2, 3)A name with a star, like *rest, collects all the leftover items into a list. Only one name can have a star.
first, *middle, last = [1, 2, 3, 4, 5]
print(first)
print(middle)
print(last)Unpacking also works in a for loop, which is perfect for a list of pairs. And it's a quick way to read two values from one line:
for name, age in [("Ana", 9), ("Bo", 11)]:
print(name, "is", age)
w, h = input("Width and height: ").split()
print("Area:", int(w) * int(h))How Python does it. Unpacking always works out the whole right side before filling any name on the left, which is why a, b = b, a can swap safely. It works with anything you can loop over: a tuple, a list, a string (a, b = "hi"), or the pairs in a for line.
Mistakes and edge cases.
- The counts don't match.
x, y = (1, 2, 3)givesValueError: too many values to unpack (expected 2, got 3)(above). - Two stars.
*a, *b = [1, 2, 3]givesSyntaxError: multiple starred expressions in assignment: Python couldn't know how to split the leftovers. - Unpacking a single number.
a, b = 5givesTypeError: cannot unpack non-iterable int object. The same error appears infor i, x in [1, 2]:, because each item is a plain number, not a pair. - A starred name can be empty.
first, *rest = [1]givesrest = [], with no error.
Quiz
What does this print?
a, b = 5, 7 a, b = b, a print(a, b)What does this print?
first, *rest = [9, 8, 7] print(rest)What does this print?
*start, last = "abc" print(start, last)What does this print?
for a, b in [(1, 2), (3, 4)]: print(a * b)What happens with
x, y = (1, 2, 3)?- A ValueError: too many values to unpack
- y gets (2, 3)
- The 3 is quietly dropped
Which line has a mistake?
nums = [1, 2] a, b, c = nums print(a + b + c)
Coding tasks
Ask for a width and a height on one line, separated by a space. Unpack them into two names and print the area (width × height).
Here is a list of pairs:
pairs = [("Ana", 9), ("Bo", 11), ("Cy", 10)]. Unpack each pair in the loop and print lines likeAna is 9.Ask for a sentence of at least two words. Print the first word, the last word, and how many words are in between, all on one line. For
the quick brown fox, printthe fox 2.