11.4 Tuple Packing and Unpacking
How comma-separated values automatically pack into a tuple, how assigning a tuple to several names unpacks it, the temp-variable-free swap idiom, and extended unpacking with the * operator.
Packing bundles values into a tuple; unpacking spreads them back out.
Packing
Writing several comma-separated values (parentheses optional) automatically bundles them into a single tuple.
>>> point = 1, 2, 3 # parentheses are optional -- this IS a tuple
>>> point
(1, 2, 3)
Unpacking
The reverse: assigning a tuple to several comma-separated names distributes its values into them, one per name.
>>> x, y, z = point
>>> x, y, z
(1, 2, 3)
Multiple Assignment and the Swap Idiom
Multiple assignment (a, b = 1, 2) is really packing and unpacking happening together in a single statement — this is also what makes the classic swap idiom work without a temporary variable.
>>> a, b = 10, 20
>>> a, b = b, a # swap -- no temp variable needed
>>> a, b
(20, 10)
Extended Unpacking
The * operator captures “everything else” into a list during unpacking — it can be placed first, last, or in the middle.
>>> first, *rest = (1, 2, 3, 4, 5)
>>> first, rest
(1, [2, 3, 4, 5])
>>> *init, last = (1, 2, 3, 4, 5)
>>> init, last
([1, 2, 3, 4], 5)
>>> a, *mid, z = (1, 2, 3, 4, 5)
>>> a, mid, z
(1, [2, 3, 4], 5)
Quick Interview Answer
“Packing is comma-separated values auto-bundling into a tuple — parentheses are cosmetic, the comma is what matters. Unpacking is the reverse: assigning a tuple to several comma-separated names. Multiple assignment is just packing the right side and unpacking it into the left side in one statement, which is exactly what makes
a, b = b, awork as a swap with no temporary variable — the right side is fully packed into a temporary tuple before any name on the left gets rebound. Extended unpacking with*namecaptures ’everything else’ into a list, and can appear anywhere in the unpacking target — first, last, or in the middle.”
Common Mistakes
- Assuming
a, b = b, aevaluates left-to-right like separate statements — the entire right-hand side is packed into a tuple first, before any assignment happens, which is exactly why it swaps correctly instead of overwritingabeforebreads it. - Unpacking a tuple into the wrong number of names —
x, y = (1, 2, 3)raisesValueError: too many values to unpack, unless a*catch-all is used to absorb the extra values. - Forgetting extended unpacking’s
*restalways produces a list, not a tuple, even though the source was a tuple.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form