Variable Assignment and Binding
Swapping two variable values is a fundamental programming operation.
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…
A Two-Value Exchange
Swapping two variable values is a fundamental programming operation. You may need to exchange two numbers while sorting, switch player positions, or reorder data. Python supports a concise form of tuple assignment that performs the exchange in one statement: a, b = b, a.
Before the final statement, a is 5 and b is 10. After it executes, a is 10 and b is 5. The important question is not only what the final values are, but how Python prevents the original value of a from being lost.
Reading Before Rebinding
What do you think happens?
Suppose a is 5 and b is 10. What are the values after a, b = b, a?
Reveal answer
a is 10 and b is 5
Python evaluates the right side first. It reads b as 10 and a as 5, then assigns those already-evaluated values to a and b in positional order.
The statement has two phases. First, Python evaluates every expression on the right side. For a, b = b, a, it looks up b and a using their current values, producing the ordered values 10 and 5. Only after that evaluation does Python assign the values to the names on the left.
Packing and Unpacking Positions
The right side supplies two ordered values. In the swap example, the values are grouped as (10, 5). The left side contains two variable names in the order a, b. Python matches the first right-side value with a and the second right-side value with b. This grouping and positional matching are the tuple assignment mechanism behind the swap.
The Complete State Change
Swapping Two Positions
Two variables represent two player positions. Exchange their values without using a separate temporary variable.
- 1Initial bindings
Let
left_positionbe 1 andright_positionbe 2. - 2Evaluate the right side
The right side reads
right_positionfirst andleft_positionsecond, producing the ordered values 2 and 1. - 3Assign by position
The first value is assigned to
left_position, and the second value is assigned toright_position.
left_position is 2 and right_position is 1.
This pattern is useful whenever two existing values need to exchange places. It can appear in sorting algorithms, data rearrangement, and situations where two positions or roles must be exchanged.
Avoiding the Overwrite Trap
Common mistake Treating the statement as two unrelated assignments that run from left to right
What it looks likea, b = b, a does not first assign b to a and then look up a again for b.
Why it failsPython evaluates all right-side expressions before making the left-side assignments.
Do this insteadTrace the right side first: read b, read a, form the ordered values, and then assign them to a and b.
Common mistake Assuming the first assignment destroys the original value needed by the second assignment
What it looks likeIf a receives b's value, it may seem that a's original value has disappeared before b can receive it.
Why it failsThe original values have already been evaluated and preserved in the ordered right-side result.
Do this insteadSeparate the operation into its two phases: complete right-side evaluation, followed by left-side assignment.
Common mistake Replacing the recognized swap pattern with unnecessary temporary-variable steps
What it looks liketemp = a; a = b; b = tempWhy it failsThis longer form works conceptually, but it takes more steps to read than Python's tuple assignment.
Do this insteadUse a, b = b, a when the goal is simply to exchange two values.
| Approach | Main steps | Readability in Python |
|---|---|---|
| Tuple assignment | Evaluate the right side, then assign by position | Concise and immediately recognizable as a swap |
| Temporary variable | Store one value, move the other value, then restore the stored value | Longer and requires more steps to parse |
Both approaches can express an exchange, but tuple assignment communicates the swap directly.
Apply the Two-Phase Trace
Trace this exchange on paper. Start with first = 12 and second = 20. After first, second = second, first, what value is bound to each variable? Explain the right-side values before describing the assignments.
Hints
- Read second and first before changing either variable.
- Place the first evaluated value into first and the second evaluated value into second.
Explain why a sequential approach that overwrites a before preserving its original value can lose information, then describe how tuple assignment avoids that problem.
Hints
- Identify which original value could be destroyed first.
- Use the two phases: evaluate all right-side expressions, then assign to the left-side names.
Essential Takeaways
- 1The statement a, b = b, a swaps the values bound to a and b in one line.
- 2Python evaluates every right-side expression before performing the left-side assignments.
- 3The evaluated values are matched positionally with the left-side variable names.
- 4Because the original values are preserved before assignment, one variable does not overwrite a value needed by the other.
- 5Tuple assignment is a concise and readable alternative to a multi-step temporary-variable swap.
At a glance
- Tuple assignment provides a one-statement way to swap two variable values.
- Right-side expressions are evaluated completely before left-side assignments occur.
- The ordered evaluated values prevent the overwriting problem associated with sequential assignment.
- The pattern is useful in sorting, data rearrangement, and exchanges of positions or roles.