Python Tuples · Lesson 49 of 149

Python Tuple Unpacking

What you will learn

  • How to unpack a tuple (or any collection) into several names
  • The rule that the counts must match, and the errors when they do not
  • Swapping and multiple assignment
  • Unpacking in for loops and from functions that return several values
  • Nested unpacking, and ignoring values with _

1. Unpacking

Unpacking takes a collection apart and gives each item its own name. The names on the left are matched to the items on the right, in order:

a, b, c = (1, 2, 3)
print(a, b, c)
px, py = (3, 4)
print(px, py)
1 2 3
3 4

You saw this with lists in lesson 7.1 and with a swap in lesson 2.1. It works on any collection you can loop over, not only tuples:

x, y = [10, 20]
p, q = "hi"
m, n = range(2)
k1, k2 = {"k": 1, "j": 2}
print(x, y, p, q, m, n, k1, k2)
10 20 h i 0 1 k j

A string gives its characters, a range its numbers, and a dictionary gives its keys (chapter 9).

Quick check: after `a, b = (5, 6)`, what is `b`?

6. The second name gets the second item.

2. Packing

The opposite of unpacking is packing: several values on the right become one tuple, because the commas make a tuple (lesson 8.1):

t = 1, 2
u = (3,)
print(t, u)
(1, 2) (3,)

So a line such as a, b = 1, 2 packs 1, 2 into a tuple and then unpacks it into a and b. This is why Python can assign several names in one line.

3. The counts must match

The number of names must equal the number of items, or Python stops with a ValueError:

Code Error
a, b = (1, 2, 3) ValueError: too many values to unpack (expected 2)
a, b, c = (1, 2) ValueError: not enough values to unpack (expected 3, got 2)
a, b = [] ValueError: not enough values to unpack (expected 2, got 0)
a, b = 5 TypeError: cannot unpack non-iterable int object

The last one fails because a number is not a collection. If the number of items can vary, lesson 8.3 shows how to collect the extras with a starred name.

4. Swapping and multiple assignment

The whole right side is worked out first, and only then assigned. That makes a swap easy, with no temporary name:

a, b = 1, 2
a, b = b, a
print(a, b)

x, y, z = 1, 2, 3
x, y, z = z, x, y
print(x, y, z)
2 1
3 1 2

Swapping two items of a list works the same way, which is the heart of many sorting algorithms:

lst = [1, 2, 3, 4]
i, j = 0, 3
lst[i], lst[j] = lst[j], lst[i]
print(lst)
[4, 2, 3, 1]

The same trick updates two values at once. This loop produces the Fibonacci numbers, where each is the sum of the two before it:

a, b = 0, 1
for _ in range(7):
    a, b = b, a + b
print(a, b)
13 21

In each pass, the new a is the old b and the new b is the old a + b, with both new values calculated before either name changes.

Chained assignment

Giving the same value to several names is a different thing:

a = b = c = 0
a += 1
print(a, b, c)
1 0 0

With numbers this is safe. With a list it is not: lst1 = lst2 = [] makes one list with two names (lesson 2.7):

lst1 = lst2 = []
lst1.append(1)
print(lst2, lst1 is lst2)
[1] True

5. Unpacking in loops

A for loop can unpack each item. You have met this already with enumerate, zip and .items() (lessons 6.2 and 6.6):

for key, value in {"a": 1, "b": 2}.items():
    print(key, value, end="; ")
print()

for n1, n2 in zip([1, 2], [10, 20]):
    print(n1 + n2, end=" ")
print()
a 1; b 2; 
11 22 

If a record has a mismatch, the loop stops with the same ValueError: for a, b in [(1, 2), (3,)] fails on the second item with not enough values to unpack (expected 2, got 1).

6. Functions that return several values

A function can return a tuple. The caller unpacks it:

def stats(nums):
    return min(nums), max(nums), sum(nums) / len(nums)

lo, hi, mean = stats([4, 9, 1, 6])
print(lo, hi, mean)

result = stats([1, 2, 3])
print(result, type(result), result[2])
1 9 5.0
(1, 3, 2.0) <class 'tuple'> 2.0

Technically the function returns one tuple. You can keep it whole and index it, or unpack it at once. Built-ins do the same: divmod(17, 5) returns (3, 2), so q, r = divmod(17, 5) gives q = 3 and r = 2. Functions are chapter 11.

7. Ignoring values with _

When you do not need some of the items, the convention is to call them _ (a plain name that means "I do not care"):

_, second, _ = (1, 2, 3)
print(second)

name, _, domain = "user@example.com".partition("@")
print(name, domain)
2
user example.com

_ is not special to Python; it is an ordinary name that programmers agree to ignore. (After the first line, _ holds the last ignored value.)

8. Nested unpacking

If an item is itself a collection, mirror its shape on the left with brackets:

(a, b), c = (1, 2), 3
print(a, b, c)

(a, (b, c)), d = (1, (2, 3)), 4
print(a, b, c, d)

for i, (name, score) in enumerate([("Rina", 90), ("Sam", 75)], 1):
    print(i, name, score, end="; ")
print()
1 2 3
1 2 3 4
1 Rina 90; 2 Sam 75; 

The shape of the left side must match the shape of the right: (a, b) for a pair inside, then c for the single value.

Worked example: reading a date and a record

Split the text "2026-10-20" into three numbers, and a record ["Rina", 25, "Dhaka"] into its fields.

year, month, day = map(int, "2026-10-20".split("-"))
print(year, month, day)

row = ["Rina", 25, "Dhaka"]
name, age, city = row
print(f"{name} ({age}) lives in {city}")
2026 10 20
Rina (25) lives in Dhaka
Step What happens
"2026-10-20".split("-") ["2026", "10", "20"] (lesson 4.4)
map(int, ...) turns each piece into a number
year, month, day = ... unpacks the three numbers into names
name, age, city = row unpacks the three fields of a record

Using three names instead of row[0], row[1] and row[2] makes the code easier to read. The record is made up.

Common mistakes

  • Mismatched counts. a, b = (1, 2, 3) is a ValueError; count the items first or use a starred name (lesson 8.3).
  • Unpacking a single number (a, b = 5).
  • Using chained assignment with a list (a = b = []), which gives one list.
  • Forgetting that the right side is worked out first, so a, b = b, a really swaps.
  • Using _ and then needing its value later.

Key takeaways

  • a, b, c = collection gives the items to the names in order; any collection works, and a dictionary gives its keys.
  • The number of names must equal the number of items, or Python raises ValueError.
  • Commas on the right pack a tuple; a, b = b, a swaps without a temporary name.
  • Loops and function results unpack naturally: for k, v in d.items(), lo, hi = min_max(values).
  • Use _ for values you ignore; mirror the shape of nested data with brackets.

Practice

1. What are x and y after x, y = "ab"?

Show answer

x is "a" and y is "b".

2. Swap the values of first and second in one line.

Show answer

first, second = second, first.

3. What error does a, b, c = [1, 2] cause?

Show answer

ValueError: not enough values to unpack (expected 3, got 2).

4. A function returns (1, 2, 3). Write a line that keeps only the middle value.

Show answer

_, middle, _ = func(), or simply middle = func()[1].

5. What do a and b hold after a, b = 1, 2 then a, b = a + b, a - b?

Show answer

a is 3 and b is -1. Both new values are worked out from the old a and b before either name changes.

6. Unpack [("x", 1), ("y", 2)] in a loop so that each pass has a letter and a number.

Show answer
for letter, number in [("x", 1), ("y", 2)]:
    print(letter, number)