Python 3D Academyবাংলা

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 = point puts point[0] in x and point[1] in y
  • packing: 1, 2 on the right of = makes a tuple first
  • starred name: *rest collects all the leftover items into a list

Step by step, for x, y = 3, 4:

  1. The right side is packed into a tuple: (3, 4).
  2. Python counts: 2 names, 2 items. They match.
  3. 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) gives ValueError: too many values to unpack (expected 2, got 3) (above).
  • Two stars. *a, *b = [1, 2, 3] gives SyntaxError: multiple starred expressions in assignment: Python couldn't know how to split the leftovers.
  • Unpacking a single number. a, b = 5 gives TypeError: cannot unpack non-iterable int object. The same error appears in for i, x in [1, 2]:, because each item is a plain number, not a pair.
  • A starred name can be empty. first, *rest = [1] gives rest = [], with no error.

Quiz

  1. What does this print?

    a, b = 5, 7
    a, b = b, a
    print(a, b)
  2. What does this print?

    first, *rest = [9, 8, 7]
    print(rest)
  3. What does this print?

    *start, last = "abc"
    print(start, last)
  4. What does this print?

    for a, b in [(1, 2), (3, 4)]:
        print(a * b)
  5. What happens with x, y = (1, 2, 3)?

    • A ValueError: too many values to unpack
    • y gets (2, 3)
    • The 3 is quietly dropped
  6. Which line has a mistake?

    nums = [1, 2]
    a, b, c = nums
    print(a + b + c)

Coding tasks

  1. 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).

  2. Here is a list of pairs: pairs = [("Ana", 9), ("Bo", 11), ("Cy", 10)]. Unpack each pair in the loop and print lines like Ana is 9.

  3. 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, print the fox 2.