Sub topic 6
Packing and Unpacking
This chapter assumes you can read basic Python syntax, build tuples and lists, index into them, and call functions. It covers what packing and unpacking do, how Python evaluates them, and the errors they raise. Later chapters cover swaps, starred targets, nested patterns, loops, and function calls in detail. Here we build the model they all rely on.
Packing: building a tuple without parentheses
A tuple is created by commas. When you write several values separated by commas on the right side of an assignment, Python collects them into one tuple. This is called packing.
point = 10, 20
print(point)
print(type(point))
record = "Ada", 1815, "London"
print(record)The parentheses you often see around tuples are only grouping. They are required when the tuple sits inside a larger expression, as in print((1, 2)), where the inner pair would otherwise look like two arguments. They are not what makes the tuple.
Packing also explains why a trailing comma matters:
single = 5,
print(single)
print(type(single))Unpacking: pulling a tuple apart
Unpacking is the reverse operation. You put several names on the left of =, separated by commas, and Python assigns one item to each name, in order.
point = 10, 20
x, y = point
print(x)
print(y)The two statements point = 10, 20 and x, y = point are mirror images. The first builds a tuple from separate values. The second splits a tuple into separate names.
You can combine both in one statement. The right side is packed and the left side is unpacked, so no tuple is visible in your code:
width, height = 1920, 1080
print(width, height)CPython often optimizes this case so it does not build a tuple at all, but the behavior is as if it did.
Unpacking works on any iterable
The right side does not have to be a tuple. Unpacking works on anything you can loop over: lists, strings, ranges, dictionaries, sets, files, generators.
a, b, c = "abc"
r0, r1 = range(2)
k1, k2 = {"x": 1, "y": 2}
first, second = [7, 8]
print(a, b, c)
print(r0, r1)
print(k1, k2)
print(first, second)Iterating a dictionary yields its keys, so k1 and k2 receive "x" and "y". To get the values or pairs you would unpack d.values() or d.items().
Sets have no guaranteed order for this purpose. p, q = {1, 2} is legal, but you should not rely on which element goes where.
An iterator is consumed by unpacking:
it = iter([1, 2, 3])
a, b, c = it
print(a, b, c)
print(list(it))The second print shows an empty list. Unpacking pulled every item out of the iterator, so nothing is left for later code.
How Python evaluates an assignment
Knowing the order of operations prevents several subtle bugs. For targets = expression, Python does this:
- Evaluate the entire right side first.
- Iterate over the result and collect its items.
- Check that the number of items matches the number of targets.
- Assign to the targets from left to right.
Step 3 comes before step 4, so a failed unpacking leaves your names unchanged:
a, b = 1, 2
try:
a, b = 10, 20, 30
except ValueError:
pass
print(a, b)This prints 1 2. Neither name was rebound.
Mismatched lengths
Without a starred target, the count must match exactly. Python raises ValueError in both directions:
for values in [(1, 2, 3), (1,)]:
try:
a, b = values
except ValueError as error:
print(error)The messages are too many values to unpack (expected 2) and not enough values to unpack (expected 2, got 1). The second one reports how many items it received. The first one cannot report a count when the source is a general iterable, because Python stops reading once it knows there is one item too many.
This strictness is useful. If a function that should return a pair starts returning three items, you find out at the unpacking line and not later with wrong data. If the length genuinely varies, use a starred target, which is covered in its own chapter.
Be careful with the type of error. A length mismatch is a ValueError. Unpacking something that is not iterable, such as a, b = 5, raises TypeError: cannot unpack non-iterable int object.
What can appear on the left
The left side is a list of targets. A target can be a plain name, but it can also be an attribute or a subscript:
class Box:
pass
box = Box()
nums = [0, 0, 0]
nums[0], box.value = 10, 20
print(nums, box.value)The left side can be wrapped in parentheses or square brackets. These forms are equivalent:
a, b = 1, 2
(a, b) = 1, 2
[a, b] = 1, 2
print(a, b)The brackets do not mean the right side must be a list. Most style guides prefer the bare form, a, b = ..., unless the pattern is nested.
| Left side | Right side | Result |
|---|---|---|
| `a, b = 1, 2` | any 2-item iterable | `a` is 1, `b` is 2 |
| `a, = [5]` | any 1-item iterable | `a` is 5, not a list |
| `a = 1, 2` | n/a | `a` is the tuple `(1, 2)` |
| `(a, b) = x` | any 2-item iterable | same as `a, b = x` |
| `a, b = 1, 2, 3` | n/a | `ValueError` |
The one-item case a, = [5] is easy to overlook. The comma turns the left side into a pattern with one target. Compare it with a = [5], which binds a to the list itself. This form is handy for extracting the only element of a result and asserting there is exactly one:
(only,) = [42]
print(only)
try:
(only,) = [1, 2]
except ValueError as error:
print(error)Order of assignment and a classic trap
Because targets are assigned left to right after the right side has been evaluated, a target that uses an earlier target can behave unexpectedly:
i = 0
items = ["a", "b", "c"]
i, items[i] = 2, "X"
print(i, items)You might expect items[0] to change, because i was 0 when the line started. The output is 2 ['a', 'b', 'X']. Python first bound i to 2, then evaluated items[i], which is now items[2]. The right side was fixed in advance, but the subscript on the left was evaluated only when its turn came.
Avoid assignments where one target depends on another target in the same statement. Split them into two lines.
Ignoring values with an underscore
When you do not need an item, a common convention is to bind it to _:
filename = "report.final.txt"
stem, _ = filename.rsplit(".", 1)
print(stem)
_, month, _ = (2026, 11, 26)
print(month)_ is an ordinary variable name. Python does not discard the value, and assigning twice to it simply rebinds it. The convention tells readers that the value is intentionally unused. Be aware that in an interactive session _ also holds the last expression result, and in code that uses gettext-style translation _ is often a function. In those cases, choose another throwaway name such as __ or unused.
Chained assignment is a different feature
Do not confuse unpacking with chained assignment, where one value goes to several names:
a = b = 1, 2
print(a, b)
print(a is b)Both names point to the same tuple. That is harmless for a tuple. With mutable values such as a = b = [], both names share one list, which often surprises people. Unpacking, by contrast, gives each target its own item.
Where packing and unpacking show up
You have already been using this mechanism, sometimes without noticing:
return a, bpacks a tuple, andx, y = f()unpacks it.for key, value in d.items()unpacks each pair on every iteration.a, b = b, apacks the right side as(b, a)and then unpacks it into the left names, which swaps them without a temporary variable.
Each of these gets its own chapter. They are all this chapter's evaluation order applied to a particular situation.
Summary of the working model
- Commas build tuples. Parentheses are optional grouping.
- Unpacking assigns items from any iterable to a list of targets, in order.
- The right side is evaluated fully first. The length check happens before any binding. Targets are then bound left to right.
- A length mismatch raises
ValueError. A non-iterable source raisesTypeError. - Targets may be names, attributes, or subscripts, and the surrounding parentheses or brackets do not change the meaning.
Exercise
Given i = 1; data = [10, 20, 30], what do i and data contain after i, data[i] = 0, 99, and why?
Show answer
i is 0 and data is [99, 20, 30]. Python evaluates the right side (0, 99) first, then assigns left to right. It binds i to 0, and only then evaluates the target data[i], which is now data[0], so 99 goes into index 0 and index 1 is untouched.
Exercise
What happens when you run x, = "ab", and what would you change so that x receives "a" without an error?
Show answer
It raises ValueError: too many values to unpack (expected 1), because the string yields two items and there is one target. Use x = "ab"[0] to take only the first character. A starred target such as x, *_ = "ab" also works.