Multiple Assignment and Simultaneous Binding
A careless sequential assignment can lose one of the original values, but Python provides a single statement that performs the exchange safely.
Try it: Assignment, Statement by Statement
How an assignment statement evaluates its right side first (using the names' current values) and only then binds the name on the left: updating x = x + 1, augmented operators like += and //=, chained a = b = 0, simultaneous a, b = b, a + b versus one-at-a-time assignment, rebinding a name to a value of another type, the NameError for a name that was never assigned, and the SyntaxError for a name that breaks the naming rules.
How it works
- Before anything runs, Python compiles the whole program; a name that breaks the rules (starts with a digit, contains a space or a dash, or is a keyword) is a SyntaxError and no line runs at all.
- For each assignment, evaluate the complete right side first, looking every name up in the variable table as it is now.
- Then bind the name(s) on the left to that value: a new name is added to the table, an existing one is replaced (even by a value of a different type).
- x += 5 reads x, applies the operator (+, -, *, //, %, **) and binds the result back to x; a = b = 0 evaluates 0 once and binds a, then b.
- a, b = b, a + b builds the whole right-hand tuple from the OLD values before binding a and b; two separate statements would use the new a in the second line.
- Reading a name that is not in the table raises NameError and the program stops at that line.
Default run (10 steps): A 4-line program. Python first compiles all of it, then runs it top to bottom. The variable table on the right starts empty. … Program finished. Final table: x = 16.
Simplified: The programs are fixed templates: you choose the template, its numbers, the operator and the variable name, never the code. The lab's own small Python tokenizer and parser (written for the statements these programs use: assignments, print calls, if / elif / else, for, while, def and return) checks the text; nothing is executed as real Python. Every program the lab can show was compiled by CPython 3.12 and the lab reproduces its exception type, message, line, caret columns and the printed report. A small interpreter written for the same statements then runs them (integers of any size, the str/float results these templates produce, and print); each program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables after every line, the output and the error.
Loading the simulation…
Why Swapping Needs Care
Swapping means exchanging the values held by two variables. This is useful when sorting numbers, exchanging player scores, or reordering data. A careless sequential assignment can lose one of the original values, but Python provides a single statement that performs the exchange safely.
What do you think happens?
Suppose a is 10 and b is 20. What will a and b contain after a, b = b, a?
Reveal answer
a is 20 and b is 10
Python first captures the current values of b and a in that order, then assigns those captured values to a and b.
The Two-Phase Assignment
The expression a, b = b, a works because Python handles it in two phases. First, Python evaluates the complete right side and creates a temporary tuple containing the current value of b followed by the current value of a. Second, Python unpacks those two values and binds them to a and b on the left side. Because both original values are captured before either variable is reassigned, neither value is lost.
a = 10
b = 20
a, b = b, a- 1Python reads the right side first, so it captures 20 and 10 before changing either variable.
- 2Python assigns the first captured value, 20, to a.
- 3Python assigns the second captured value, 10, to b.
- The variables begin with different values.
- The right side is evaluated as the current value of b followed by the current value of a.
- The captured values are unpacked into a and b.
After the swap, a is 20 and b is 10.A Complete Swap Trace
Exchange Two Scores
Exchange the values of player_one_score and player_two_score without writing an explicit temporary variable.
- 1Starting values
player_one_scoreis 45 andplayer_two_scoreis 60. - 2Write the values in reverse order
Place
player_two_scorefirst andplayer_one_scoresecond on the right side:player_one_score,player_two_score=player_two_score,player_one_score. - 3Evaluate the right side
Python captures the current values as 60 and 45 before assigning either result.
- 4Unpack to the left side
The first captured value goes to
player_one_score, and the second goes toplayer_two_score.
player_one_score is 60 and player_two_score is 45.
Why the Idiom Is Preferred
| Tuple unpacking | Temporary-variable method |
|---|---|
| a, b = b, a | Uses several explicit assignment steps |
| No explicitly written temporary variable | Requires a temporary holding variable to preserve an original value |
| Concise and readable | More verbose |
| Python optimizes this common pattern and executes it more efficiently | The source describes tuple unpacking as less efficient than this pattern |
Both approaches can exchange two values, but tuple unpacking is the preferred Python idiom according to the source material.
Mistakes That Break a Swap
Common mistake Using sequential assignment without preserving the first 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 has been lost, so the second assignment cannot recover it.
Do this insteadUse a, b = b, a so Python captures both original values before either variable is reassigned.
Common mistake Forgetting the comma syntax
What it looks likea = b, aWhy it failsThe left side no longer names two variables for unpacking, so the statement does not express the intended two-variable swap.
Do this insteadWrite two targets separated by a comma: a, b = b, a.
Common mistake Writing the right-side values in the wrong order
What it looks likea, b = a, bWhy it failsThe values are assigned in their original order, so this does not exchange them.
Do this insteadReverse the right-side order: a, b = b, a.Common mistake Accidentally rotating more than two variables
What it looks likea, b, c = b, c, aWhy it failsThis statement moves three values according to a three-variable order rather than performing a simple two-variable swap.
Do this insteadFor a two-variable swap, use exactly two targets and place their names in reverse order on the right side.
Practice the Binding Order
Write a Python statement that swaps the values of first_item and second_item. Then explain which original value is evaluated first on the right side and where it is assigned on the left side.
Hints
- Use two names on the left side separated by a comma.
- Place the names in reverse order on the right side.
- The first value evaluated on the right side is the current value of
second_item.
Debug this attempted swap: a = 3; b = 8; a = b; b = a. Identify the original value that is lost and rewrite the code using simultaneous binding.
Hints
- Trace the values immediately after the first assignment.
- The original value of a must be captured before a changes.
- The corrected form places b first on the right side and a second.
The Pythonic Pattern
- 1For a two-variable swap, write a, b = b, a. Python evaluates the complete right side first, preserving both original values in an internal temporary tuple. It then unpacks those values into the left-side variables. This approach is concise, readable, and described in the source as faster and more efficient than the traditional temporary-variable method. When debugging, check the comma syntax, the order of the names, and whether a sequential assignment has accidentally overwritten an original value.
Key Takeaways
- Tuple unpacking swaps two values with the syntax a, b = b, a.
- Python evaluates the right side completely before assigning to the left side.
- The current value of b becomes the new value of a, and the current value of a becomes the new value of b.
- The tuple-unpacking pattern is concise, readable, and described as more efficient than the traditional temporary-variable approach.
- Common errors include sequential assignment without a temporary value, missing comma syntax, incorrect order, and accidentally rotating more than two variables.