Variable Swapping Using Tuple Assignment
Unpacking is a syntactic feature that assigns multiple variables from a sequence in one statement, equivalent to index-based assignment.
Try it: Tuples: Comparison and Unpacking
How Python compares tuples lexicographically — the first unequal pair of items decides, a shorter prefix is smaller, int vs str ordering raises TypeError — and how tuple assignment unpacks and swaps values.
How it works
- Walk both tuples from index 0 while the items are equal.
- At the first difference, that pair alone decides (later items are never looked at); strs compare by code point.
- If one tuple runs out first, the shorter one is smaller; ordering an int against a str raises TypeError.
- Unpacking checks the count first: too many or too few values raise ValueError before any name is bound.
- a, b = b, a builds the right-hand tuple from the old values, then unpacks it into the names.
Default run (4 steps): Evaluate (1, 'pear', 7) < (1, 'plum', 2): compare item by item from index 0. … 'pear' < 'plum' is True (strings compare by code point: 'e' is 101, 'l' is 108), so (1, 'pear', 7) < (1, 'plum', 2) is True.
Simplified: Flat tuples of up to 6 ints or short ASCII strs (no nested tuples, floats or starred targets).
Loading the simulation…
The One-Line Swap
Tuple assignment lets one statement assign values to multiple variables. The same unpacking pattern can swap two values: the value currently associated with a is assigned to b, while the value currently associated with b is assigned to a.
What do you think happens?
After these statements run, what values are associated with a and b?
a, b = 10, 20a, b = b, a
Reveal answer
a is 20 and b is 10
The second statement unpacks the two values in the order b, a into the targets a, b. The value from b goes to a, and the value from a goes to b.
Position Controls Assignment
Unpacking assigns sequence elements to variables by position. In x, y = sequence, the first element is assigned to x and the second element is assigned to y. The number of variables must exactly match the number of elements being unpacked.
values = (7, 12)
x, y = values- 1The sequence has the elements 7 and 12.
- 2The target list has x and y.
- 3The first position maps 7 to x.
- 4The second position maps 12 to y.
- values contains two sequence elements.
- x is the first target, so it receives the first element.
- y is the second target, so it receives the second element.
x is 7 and y is 12Unpacking and Index Assignment
Unpacking is a syntactic feature that assigns multiple variables from a sequence in one statement. It is equivalent to assigning the values by their indexes.
| Unpacking form | Index-based form |
|---|---|
| x, y = sequence | x = sequence[0]; y = sequence[1] |
| first, second = values | first = values[0]; second = values[1] |
The two forms express the same positional mapping described by the source material.
Tuples Lists and Strings
Unpacking works uniformly with tuples, lists, strings, and any sequence type. The source sequence can differ, but the assignment rule remains positional: the first element goes to the first variable, the second element goes to the second variable, and so on.
first is 3 and second is 4
left is 8 and right is 9
letter_one is h and letter_two is iMatching Element Counts
The number of target variables must exactly match the number of elements in the source sequence. If there are too many or too few targets, unpacking cannot complete and causes a ValueError.
a, b = [1, 2, 3]Two variables receive three elements, so unpacking fails.
a, b, c = [1, 2, 3]Three variables receive three elements, so the counts match.
Common mistake Using fewer variables than elements
What it looks likea, b = [1, 2, 3]Why it failsThere are two target variables but three source elements.
Do this insteadUse three variables, such as a, b, c = [1, 2, 3].
Common mistake Using more variables than elements
What it looks likea, b, c = [1, 2]Why it failsThere are three target variables but only two source elements.
Do this insteadMake the number of variables equal to the number of elements.
Common mistake Assuming the source type changes the positional rule
What it looks likefirst, second = "hi"Why it failsA string is still unpacked by position, just like a tuple or list.
Do this insteadCount the string's sequence elements and match them with the target variables.
A Reliable Unpacking Check
- 1Identify the source sequence.
- 2Count its elements.
- 3Count the target variables.
- 4Match the first source element with the first target, the second with the second, and so on.
- 5If the counts differ, add or remove target variables before running the assignment.
- 6For a swap, place the variables in the opposite order on the right side.
Tracing a Three-Element Unpack
Determine the values assigned by first, second, third = [4, 5, 6].
- 1Count the source elements
The list contains three elements: 4, 5, and 6.
- 2Count the targets
There are three target variables: first, second, and third.
- 3Map positions
The first element 4 goes to first, 5 goes to second, and 6 goes to third.
first is 4, second is 5, and third is 6.
Practice the Mapping
For each statement, identify the value assigned to every variable. Then decide whether any statement causes a ValueError.
- left, right = (2, 9)
- first, second, third = ["a", "b", "c"]
- one, two = "cat"
- score, best = 40, 75
- score, best = best, score
Hints
- Map elements from left to right.
- Check that the number of variables equals the number of sequence elements.
- For the final statement, read the right side in the order best, score.
1. left is 2 and right is 9.
2. first is a, second is b, and third is c.
3. The statement causes a ValueError because the string provides three elements and there are only two variables.
4. score is 40 and best is 75.
5. score becomes 75 and best becomes 40.Key Takeaways
- 1Unpacking assigns multiple variables from one sequence in a single statement.
- 2Assignment follows position: the first element goes to the first variable, the second element goes to the second variable, and so on.
- 3Unpacking is equivalent to index-based assignment such as x = sequence[0] and y = sequence[1].
- 4Tuples, lists, strings, and other sequence types can be unpacked using the same positional rule.
- 5The number of variables must exactly match the number of elements, or a
ValueErroroccurs. - 6Writing the variables in reverse order on the right side provides a concise way to swap their values.
At a glance
- Unpacking maps sequence elements to multiple variables by position.
- Tuple assignment can swap two variable values in one statement.
- The same unpacking approach works with tuples, lists, and strings.
- Unpacking corresponds to index-based assignment.
- A mismatch between target variables and source elements causes a
ValueError.