CurriculumPython Variables for KidsSwapping and Tracing
Swapping Two Python Variables in One Line
left, right = right, left swaps two boxes in one line — and why the obvious two-line swap actually fails.
Swapping and Tracing
You know how to change ONE box at a time. Here's how to trade the values in TWO boxes at once.
left, right = right, left swaps them. Python builds the whole right side first — (right, left) — THEN hands it back to left and right.
left = 1
right = 2
left, right = right, left
print(left, right)Output
2 1Why not just do it the obvious way — left = right, then right = left? Watch closely.
left = right overwrites left's original 1 immediately. By the time right = left runs, left's old value is already gone.
left = 1
right = 2
left = right
right = leftSo right = left doesn't copy the OLD left — it copies the NEW left, which is already 2. Both boxes end up the same.
left = 1
right = 2
left = right
right = left
print(left, right)Output
2 2left, right = right, left never has this problem, because Python reads BOTH old values — building the pair (right, left) — before changing either box.
left = 1
right = 2
left, right = right, left
print(left, right)Output
2 1One more trick: left = right = 0 sets BOTH boxes to 0 at once. It's the same right-side-first rule, just with one value instead of two.
left = right = 0 gives them the same starting value — but they're still two separate boxes from then on.
left = right = 0
left = left + 1
print(left, right)Output
1 0Check your understanding
left = 1, right = 2, then left = right, then right = left. What does print(left, right) show?
left = 1
right = 2
left = right
right = left
print(left, right)Why: left = right overwrites left's 1 with right's 2 — that original 1 is gone for good. Then right = left copies the CURRENT left, which is already 2. Both boxes end up holding 2, the value right started with. This is exactly why a real swap needs left, right = right, left (or a temporary third box) instead.
left = 5, right = 9, then left, right = right, left. What does print(left, right) show?
left = 5
right = 9
left, right = right, left
print(left, right)Why: left, right = right, left builds the pair (right, left) — (9, 5) — using both OLD values first, before touching left or right at all. Only then does it assign 9 to left and 5 to right. That's the whole trick: read everything first, assign everything after, so neither box's old value can be lost mid-swap the way the naive version loses it.
What you'll practice
left = 5 and right = 9. Print both, labelled, before anything happens. Then swap them in one line — left, right = right, left — and print both again, labelled. left should now be 9, and right should now be 5.
More from this topic
Swapping and Tracing is one lesson inside Python Variables for Kids — see the full lesson order and what the whole topic covers.
View the full topic →