Tuple Creation and Unpacking
The internal temporary tuple is handled automatically.
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 Swap Problem
Swapping means exchanging the values held by two variables. This is useful when sorting numbers, exchanging player scores, or reordering data in a collection. In many programming languages, a temporary holding variable is needed so that the first value is not lost. Python provides a single-statement alternative: a, b = b, a.
After the swap, a contains 20 and b contains 10.Evaluation Before Assignment
The statement a, b = b, a works because Python evaluates the entire right side before assigning anything to the left side. With a equal to 10 and b equal to 20, Python first captures the current values on the right in this order: 20, then 10. It then assigns the first captured value to a and the second captured value to b. The original values are therefore preserved before either variable changes.
A Complete Swap Trace
Exchanging Two Scores
Start with score_a equal to 42 and score_b equal to 17. Exchange their values using tuple unpacking.
- 1Initial state
score_a contains 42 and score_b contains 17.
- 2Evaluate the right side
The right side score_b, score_a produces the values 17 and 42 in that order before either assignment occurs.
- 3Unpack to the left side
The first captured value is assigned to score_a, and the second captured value is assigned to score_b.
score_a contains 17 and score_b contains 42.
score_a = 42
score_b = 17
score_a, score_b = score_b, score_a- 1The first line gives score_a the value 42.
- 2The second line gives score_b the value 17.
- 3The third line captures the current right-side values in the order score_b, score_a and assigns them to the left-side variables in the order score_a, score_b.
- score_a starts with 42.
- score_b starts with 17.
- The right side is evaluated as 17, 42, then those values are assigned to score_a and score_b.
score_a is 17 and score_b is 42.Why This Form Is Preferred
| Tuple unpacking | Temporary-variable method |
|---|---|
| a, b = b, a | temp = a; a = b; b = temp |
| One statement | Several assignment statements |
| No explicitly named temporary variable | Requires a temporary holding variable |
| Concise, readable, and recognized as a swap | Longer sequence that must preserve the first value manually |
| Python optimizes this common pattern and executes it more efficiently | Traditional approach is less efficient according to the source material |
Both approaches exchange the values, but tuple unpacking is the more concise, readable, and efficient Python approach.
Tuple unpacking is not merely shorter syntax. The source describes this pattern as genuinely faster because Python's interpreter optimizes it as a common operation. It is also immediately recognizable to programmers as a swap, which improves readability.
Mistakes That Lose Values
Common mistake Assigning sequentially without a temporary value
What it looks likea = b b = aWhy it failsAfter the first assignment, a contains the original value of b. The original value of a is no longer available, so the second assignment gives b that same value instead of completing a swap.
Do this insteadUse a, b = b, a, or use a separately named temporary variable.
Common mistake Forgetting the comma syntax
What it looks likea = b a = aWhy it failsThis is not a two-variable unpacking assignment. It performs separate assignments and does not exchange the values.
Do this insteadWrite both target variables and both source values: a, b = b, a.
Common mistake Reversing the right-side order incorrectly
What it looks likea, b = a, bWhy it failsEach variable receives its own current value, so no swap occurs.
Do this insteadPlace the source variables in the opposite order: a, b = b, a.
Common mistake Accidentally rotating more than two variables
What it looks likea, b, c = b, c, aWhy it failsThis assigns values in a three-variable rotation rather than swapping only a and b.
Do this insteadFor a two-variable swap, include only the two target variables and put their values in reversed order.
Practice the Pattern
Suppose first_item contains 3 and second_item contains 8. Write one Python statement that exchanges their values without creating a named temporary variable.
Hints
- Put the two target variables on the left side.
- Put the same variables in reverse order on the right side.
- The pattern is target_a, target_b = source_b, source_a.
What do you think happens?
Before running the statement first_item, second_item = second_item, first_item, what values will the variables contain afterward?
Reveal answer
first_item contains 8 and second_item contains 3.
Python evaluates the right side first, capturing second_item's value of 8 and first_item's value of 3. It then assigns those captured values to first_item and second_item in that order.
Key Takeaways
- 1The standard Python swap statement is a, b = b, a.
- 2Python evaluates the entire right side before assigning to the left side.
- 3The captured right-side values are then unpacked into the left-side variables, so neither original value is lost.
- 4Tuple unpacking is concise, readable, and faster than the traditional temporary-variable approach according to the source material.
- 5Sequential assignment without a temporary value, incorrect ordering, and accidental multi-variable rotations are common mistakes.
At a glance
- Use a, b = b, a to exchange two variable values in one statement.
- Python captures the right-side values before changing either left-side variable.
- Tuple unpacking avoids an explicitly named temporary variable and is concise, readable, and efficient.
- Do not replace the swap with sequential assignments such as a = b followed by b = a.
- Check the order and number of values whenever unpacking does not produce the expected result.