PYTHON INTERMEDIATEChapter 6 · Comprehensions and data tools
Unpacking values
Unpacking assigns several variables at once from a sequence: x, y = (3, 4). It is how you swap two values in one line (a, b = b, a) and how a function hands back more than one result. A starred name collects whatever is left: first, *rest = [1, 2, 3].
Worked example
How it reads
- The number of names on the left must match the number of values
return a, breturns a tuple, which you unpack straight away*middlesoaks up the values in between as a list
Common mistakes
x, y = [1, 2, 3]raises ValueError: too many values to unpack.

Cloud tip: Unpacking works in loops too:
for name, mag in pairs: unpacks each pair as you go.

