Variable Swapping with Tuples
Count the variables on the left and the values on the right. The two counts must be equal.
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 Matching Rule
Tuple assignment works only when the number of variables on the left exactly matches the number of values on the right. Python checks this requirement before assigning any values. If the counts differ, Python raises a ValueError instead of guessing what you intended.
Count the variables on the left and the values on the right. The two counts must be equal.
Position-by-Position Mapping
Python pairs each variable with the value in the same position. In the assignment a, b = 1, 2, the first variable receives the first value, and the second variable receives the second value. Every variable has one partner, so the assignment can complete.
A Complete Mapping
Analyze the assignment a, b = 1, 2.
- 1Count the variables
There are two variables on the left: a and b.
- 2Count the values
There are two values on the right: 1 and 2.
- 3Match positions
Variable a is paired with value 1 at position 0, and variable b is paired with value 2 at position 1.
The counts match, so the assignment completes successfully.
Why Python Stops Early
A mismatch means Python cannot create a complete position-based mapping. With too many values, some values would have no variable. With too few values, some variables would have no value. Python stops and raises a ValueError rather than dropping values, creating defaults, or nesting values in an unexpected way.
Reading the ValueError
What do you think happens?
What happens when Python tries to assign three values to only two variables?
Reveal answer
Python raises a ValueError before the assignment completes.
The counts do not match, so Python cannot create a complete position-based mapping. The error identifies the mismatch as too many values for the expected number of variables.
Three Values, Two Variables
Analyze the attempted assignment a, b = 1, 2, 3.
- 1Count the left side
The left side contains two variables: a and b.
- 2Count the right side
The right side contains three values: 1, 2, and 3.
- 3Read the message
Python reports: too many values to unpack (expected 2). The expected count is two because there are two variables, but three values were provided.
- 4Check assignment state
The
ValueErroris raised before any assignment occurs. The attempted assignment does not complete.
The source of the failure is one extra value on the right side.
Debugging the Mismatch
Use the ValueError message as your first debugging clue. A message saying too many values to unpack means the right side contains more values than the left side has variables. A message saying too few values to unpack means the left side has more variables than the right side has values. Then inspect both sides and locate the count difference.
Common mistake Assuming Python will ignore an extra value.
What it looks likeUsing two variables with three values.
Why it failsPython requires every value to have a matching variable and raises a
ValueErrorwhen a value is left over.Do this insteadCount both sides and make the number of variables equal to the number of values.
Common mistake Assuming Python will invent a value for a variable that has no match.
What it looks likeUsing three variables with only two values.
Why it failsPython does not guess a missing value. A variable without a corresponding value prevents the position-based mapping from completing.
Do this insteadProvide a value for every variable on the left.
Common mistake Looking only at the variable names instead of the values being unpacked.
What it looks likeChecking a, b but not counting the values on the right.
Why it failsThe error is caused by the relationship between both sides of the assignment.
Do this insteadCount the variables and values together, then use the wording of the ValueError to identify the direction of the mismatch.
Common mistake Expecting a partial assignment before the error.
What it looks likeAssuming the first variable receives a value even though a later value has no destination.
Why it failsPython checks the count before any assignment occurs.
Do this insteadTreat the failed assignment as incomplete; the variables retain their previous values.
Practice the Count Check
For each assignment, decide whether the tuple assignment can complete. If it cannot, identify whether there are too many or too few values: first, x, y = 4, 5; second, left, middle, right = 10, 20, 30; third, p, q = 7, 8, 9.
Hints
- Count the variables on the left before interpreting the values.
- Count the values on the right separately.
- Use the direction of the count difference to classify the mismatch.
- 1Count the variables on the left.
- 2Count the values on the right.
- 3If the counts match, map each position to the corresponding position.
- 4If the counts differ, read the
ValueErrorwording to determine whether values are too many or too few. - 5Inspect the assignment before changing it, because no variable is modified when the count check fails.
Key Takeaways
- 1Tuple assignment requires exactly equal counts of variables and values.
- 2Python maps values to variables by position.
- 3A mismatch raises a
ValueErrorbefore assignment occurs. - 4Too many values and too few values produce different diagnostic wording.
- 5Counting both sides of an assignment is the fastest way to prevent and debug unpacking failures.
At a glance
- Tuple assignment succeeds only when both sides contain the same number of items.
- Position determines which value is paired with each variable.
- Python raises
ValueErrorbefore assignment when the counts differ. - The error message identifies whether there are too many or too few values.
- Debugging starts by counting variables and values and locating the mismatch.