Understanding Python's Assignment Model
Python provides a shorter assignment pattern: a, b = b, a.
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…
The Swap Problem
Swapping two variables means exchanging the values currently associated with their names. This is useful when sorting numbers, exchanging player scores, or reordering data in a collection. In many programming languages, the usual solution requires a temporary holding variable so that the first value is not lost. Python provides a shorter assignment pattern: a, b = b, a.
What do you think happens?
Suppose a refers to 5 and b refers to 10. What values will a and b have after a, b = b, a?
Reveal answer
a is 10 and b is 5
The right side is evaluated as the current values of b and a, in that order. Those values are then assigned to a and b on the left.
The Two-Phase Assignment
Python safely performs the swap in two phases. First, it evaluates the entire right side, b, a, using the current values of the variables. Python internally preserves those values in a temporary tuple. Second, it unpacks the preserved values and assigns them to the names on the left, a and b. Because both original values are captured before either name is reassigned, neither value is lost.
Mapping Values to Names
The positions determine the swap. The first value on the right, the current value of b, is assigned to the first name on the left, a. The second value on the right, the current value of a, is assigned to the second name on the left, b. The comma syntax creates the multiple-value structure that Python unpacks.
Exchanging Two Scores
Let a represent 5 and b represent 10. Apply a, b = b, a.
- 1Read the right side
The right side supplies the current values of b and a, which are 10 and 5.
- 2Preserve both values
Python preserves the pair 10 and 5 before changing either left-side name.
- 3Assign by position
The first preserved value goes to a, and the second preserved value goes to b.
a represents 10 and b represents 5.
Why This Pattern Is Preferred
| Approach | Explicit steps | Intermediate storage | Clarity |
|---|---|---|---|
| Tuple unpacking | One assignment statement | Handled internally by Python | Concise and immediately recognizable as a swap |
| Temporary variable | Several assignments | An explicitly named temporary variable | Correct but more verbose |
Both approaches exchange two values, but tuple unpacking expresses the operation more directly.
Tuple unpacking is more concise, readable, and efficient than the traditional temporary-variable approach. The source describes it as faster because Python's interpreter optimizes this common pattern. The practical benefit is also communicative: a, b = b, a immediately signals to another programmer that the operation is a swap.
Mistakes That Lose Values
Common mistake Using sequential assignment without preserving the original value
What it looks likea = b; b = aWhy it failsAfter the first assignment, a has b's original value. The original value of a is no longer available for the second assignment.
Do this insteadUse a, b = b, a, which evaluates the right side before assigning either left-side name.
Common mistake Forgetting the comma syntax
What it looks likea = b = aWhy it failsThis does not express two corresponding positions for tuple unpacking and does not perform the intended exchange.
Do this insteadWrite both names and both right-side values with comma separators: a, b = b, a.
Common mistake Accidentally rotating more than two variables
What it looks likea, b, c = b, c, aWhy it failsThe values are assigned according to all three positions, so this performs a three-variable rotation rather than a two-variable swap.
Do this insteadFor a two-variable swap, include exactly the two intended names and their two corresponding right-side values.
Common mistake Providing a different number of values on the two sides
What it looks likea, b = bWhy it failsThe left side names two positions, while the right side provides one value, so the assignment cannot map one value to each name.
Do this insteadEnsure that the number of unpacked values matches the number of target names.
Practice the Pattern
Suppose a represents 12 and b represents 3. Write the single Python assignment statement that exchanges their values. Then state the value represented by each name after the assignment.
Hints
- Put the two target names on the left, separated by a comma.
- Put the values in reverse name order on the right.
- The right side is evaluated before either left-side name changes.
A learner writes a = b; b = a to swap two values. Explain why the result is incorrect and rewrite the operation using tuple unpacking.
Hints
- Track the value of a immediately after the first assignment.
- Ask whether the original value of a is still available for the second assignment.
- Use the two-phase evaluation behavior of a, b = b, a.
The Essential Takeaways
- 1Python swaps two values with the concise statement a, b = b, a.
- 2Python evaluates the complete right side before assigning to the left side.
- 3The internally preserved values prevent the original values from being lost.
- 4The comma positions map the first right-side value to the first left-side name and the second right-side value to the second left-side name.
- 5Tuple unpacking is more concise, readable, and efficient than explicitly writing a temporary-variable swap.
At a glance
- Tuple unpacking lets Python exchange two variable values in one statement.
- The right side is evaluated first, preserving both original values before assignment occurs.
- In a, b = b, a, the right-side values map to the left-side names by position.
- Sequential assignment can overwrite a value, while missing commas or mismatched value counts prevent the intended unpacking.
- The tuple-unpacking form is concise, readable, efficient, and recognizable as the Python swap idiom.