Beginner Chapter 48 · 25 min read · Module 4: Python Data Structures
Tuple Packing and Unpacking
- After this chapter you can pack several values into one tuple and unpack them into separate names.
- You can swap two variables without a temporary variable.
- You can use * to collect extra items during unpacking.
- You can unpack nested tuples and loop over a list of tuples.
- You can return several values from a function and receive them with unpacking.
Tuples are often used to carry a small group of related values, such as a name and an age, or the x and y of a point. Python makes it very easy to put values into a tuple and to take them out again. These two actions are called packing and unpacking.
Unpacking is one of the features that makes Python code short and clear. You will see it in for loops, in functions that return more than one value, and in the famous one-line swap of two variables.
In this chapter you will learn the basic rules, the star form for collecting extras, and the common mistakes, such as using the wrong number of names on the left side.
Packing values
Packing means putting several values into one tuple. You do not even need brackets: when you write values separated by commas, Python builds a tuple for you. The brackets are only needed in some places, for example inside a function call, or to show an empty tuple.
point = 3, 4.point = 3, 4
person = ("Asha", 21, "Pune")
print(point, type(point).__name__)
print(person)
single = 5,
print(single)Unpacking values
Unpacking means assigning the items of a tuple to separate variables in one statement. The number of names on the left must match the number of items on the right, or Python raises ValueError. Unpacking works with any iterable, such as lists and strings, not just tuples.
name, age, city = ("Asha", 21, "Pune")
print(name)
print(age, city)
x, y = [10, 20]
print(x + y)
a, b, c = "abc"
print(c, b, a)
try:
p, q = (1, 2, 3)
except ValueError as e:
print(e)Swapping without a temporary variable
On the right side of a, b = b, a, Python first packs the current values of b and a into a tuple. Then it unpacks that tuple into a and b. Because the right side is finished before any assignment happens, nothing is lost. This is why no third variable is needed.
first = "left"
second = "right"
first, second = second, first
print(first, second)
a, b, c = 1, 2, 3
a, b, c = c, a, b
print(a, b, c)Star unpacking (Python 3)
When you do not know how many items there are, put a * before one name. That name collects all the items that are not matched by the other names, and it is always a list, even when it collects nothing. Only one starred name is allowed in a single unpacking. The starred form also works in the middle.
first, *rest = (1, 2, 3, 4)
print(first, rest)
*body, last = (1, 2, 3, 4)
print(body, last)
head, *middle, tail = (10, 20, 30, 40, 50)
print(head, middle, tail)
one, *none = (7,)
print(one, none)
_, value, _ = ("skip", 42, "skip")
print(value)_ is a common name for a value you do not care about. It is only a habit; Python treats it as an ordinary variable.Nested unpacking and loops
If a tuple holds other tuples, the pattern on the left can have the same shape. This is very handy in a for loop over a list of pairs or over enumerate() and dict.items(), because each round of the loop unpacks one item.
line = ("Asha", (3, 4))
name, (x, y) = line
print(name, x, y)
students = [("Ravi", 80), ("Mina", 95)]
for who, mark in students:
print(who, "scored", mark)
for i, (who, mark) in enumerate(students, start=1):
print(i, who, mark)It helps to know what is really stored. After point = 3, 4, the name point refers to one tuple object that holds two items. When you unpack it into x, y, the tuple is not changed or destroyed; the two new names simply refer to the items. If the items are mutable, such as lists, both the tuple and the new name refer to the same list object, so a change made through one is visible through the other.
Unpacking is also a good way to make code easier to read. Compare row[0] and row[2] with name, _, city = row. The second form tells the reader what each position means. When a record has many fields, prefer a named tuple or a small class, but for two or three values plain unpacking is perfect.
Returning several values from a function
A function can only return one object, but that object can be a tuple. When you write return a, b, Python packs the two values. The caller then unpacks the result into two names. This is the usual way to give back more than one result.
def low_high(numbers):
return min(numbers), max(numbers)
result = low_high([4, 9, 1, 7])
print(result)
low, high = low_high([4, 9, 1, 7])
print(low, high)You can also unpack with * in a function call. If args = (2, 3), then pow(*args) means pow(2, 3). This is a close relative of unpacking and is used a lot in real programs.
Python syntax
packed = a, b, cx, y, z = packedfirst, *rest = iterablea, b = b, adef f(): return v1, v2Real-world applications
- Returning a result and a status from a function.
- Looping over pairs from zip, enumerate and dict.items().
- Swapping values in sorting algorithms.
- Splitting a record such as a CSV row into named fields.
Common mistakes
a, b = (1, 2, 3).Fix: Match the counts, or use a starred name:
a, *b = (1, 2, 3).Fix: Wrap it with tuple() if you need a tuple.
Fix: Only one * is allowed per unpacking.
a = b = (1, 2) when you wanted to unpack.Fix: Use
a, b = (1, 2); the chained form gives both names the same tuple.Important tips
- Use unpacking in for loops to give meaningful names instead of indexes like pair[0].
- Use _ for values you will not use.
- Use unpacking to swap values; it is shorter and clearer.
Key points summary
- Commas make a tuple; brackets are often optional.
- Unpacking needs matching counts unless a starred name is used.
- The starred name always becomes a list.
- a, b = b, a swaps two values.
- A function returning several values really returns one tuple.
Exam and interview points
- Packing is making a tuple with commas; unpacking assigns items to names.
- Mismatched counts raise ValueError.
- *rest collects extra items into a list.
- Multiple return values are returned as a tuple.
Quick revision
- x, y = 1, 2 packs and unpacks in one line.
- a, b = b, a swaps.
- first, *rest = items.
- return a, b gives a tuple.
Frequently asked questions
Does unpacking work with lists and strings?
Yes. Any iterable works, as long as the number of items matches the number of names.
What if the starred name gets no items?
It becomes an empty list. For example, a, *b = (1,) gives a = 1 and b = [].
Is the swap really safe?
Yes. The right side is fully evaluated into a tuple before any name is assigned.
Can I unpack a dictionary?
Unpacking a dictionary gives its keys. Use d.items() to get key and value pairs.
Practise this chapter
23 practice questions Take the chapter quiz