Swapping two variables in Python

Watch values move between memory boxes as Python executes a temp-variable swap one line at a time — and see exactly what goes wrong without it.

Python Beginner Variables · Assignment ~5 min
Why swapping needs care

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.

TipBefore you overwrite a variable, ask: “do I still need its old value?”
PitfallThe naive attempt
naive.pyPython
a = 5
b = 10
a = b   # a is now 10 … 5 is lost
b = a   # b = 10, not 5
expected
a = 10, b = 5
actual
a = 10, b = 10 5
See it fail in the simulator →
Interactive

Run the simulation

The highlighted line is being executed. Each box is a variable with its name and current value.

Step 0 / 5
swap_temp.pyPython
Variablestemp-variable swap
Variables
No variables yet — press Step or Play to run the first line.
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Trace it

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.

With a temp variableCorrect
Lineabtemp
a = 55——
b = 10510—
temp = a5105
a = b10105
b = temp1055
Final: a = 10, b = 5 ✓
Run this program →
Without a temp variableBroken
Lineabtemp
a = 55——
b = 10510—
a = b10 510—
b = a1010—
 
Final: a = 10, b = 10 ✗ (5 is lost)
Run this program →
Watch out

Common mistakes to avoid

Even with a temp variable, the order of the three lines matters.

Saving the wrong value
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.

Saving too late
a = b
temp = a   # 5 is already gone
b = temp

The copy must happen before the overwrite. Here temp captures 10, not 5.

The pattern to remember
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.