Assignment overwrites
You want a to hold b’s value and b to hold a’s value. But Python runs one statement at a time, and the moment you write a = b, the original value of a is replaced.
So a correct swap must keep a copy of one value before it gets overwritten. That’s the job of a third variable, usually called temp.
a = 5 b = 10 a = b # a is now 10 … 5 is lost b = a # b = 10, not 5
a = 10, b = 5
a = 10, b = 10
Run the simulation
The highlighted line is being executed. Each box is a variable with its name and current value.
Why the temp variable is needed
Both programs side by side. The only difference is one extra line — and that line keeps the value 5 alive.
| Line | a | b | temp |
|---|---|---|---|
| a = 5 | 5 | — | — |
| b = 10 | 5 | 10 | — |
| temp = a | 5 | 10 | 5 |
| a = b | 10 | 10 | 5 |
| b = temp | 10 | 5 | 5 |
| Line | a | b | temp |
|---|---|---|---|
| a = 5 | 5 | — | — |
| b = 10 | 5 | 10 | — |
| a = b | 10 | 10 | — |
| b = a | 10 | 10 | — |
Common mistakes to avoid
Even with a temp variable, the order of the three lines matters.
temp = a b = a # should be a = b a = temp
Both end up as 5. Whatever you save in temp, the next line must overwrite that same variable.
a = b temp = a # 5 is already gone b = temp
The copy must happen before the overwrite. Here temp captures 10, not 5.
temp = a # 1. save a a = b # 2. overwrite a b = temp # 3. restore into b
Each line’s right side is the previous line’s left side: a → temp, b → a, temp → b.