Python Tuple Unpacking and Swapping
Core idea
Unpacking assigns the items of a sequence to separate targets. In x, y = point, the right side must provide exactly two items. The right side is evaluated before the assignments occur, so the same syntax can swap two existing values.
delivery = ("North", 12)zone, count = deliveryprint(zone, count)The first item goes to zone and the second to count.
Swap two readings
left = 3right = 9left, right = right, leftprint(left, right)Both old values are read before either name is rebound.
Intentional error: too many items
The three items cannot fit two targets without a starred target.
Common mistake
Unpacking works on lists and other iterable values too. Ordinary unpacking requires the exact target count; it does not silently discard extra items.
Practice
Unpack (7, 11) into width and height, then swap them and print the new dimensions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tuple unpacking
Check your understanding of tuple unpacking.
What is printed?
a, b = 2, 6a, b = b, aprint(a, b)What is printed?
x, y = [4, 9]print(y)Which error occurs?
a, b = (7,)What must ordinary unpacking match?