Swap Two Variables in Python
Trace two Python swaps side by side: a temporary variable and tuple unpacking. New programmers can see exactly when each original value is read and replaced.
1# Swapping using a temporary variable2a = 53b = 1045temp = a6a = b7b = temp89print("After swapping (using temp): a =", a, "b =", b)1011# Swapping using Python tuple unpacking12x = 513y = 101415x, y = y, x1617print("After swapping (tuple unpacking): x =", x, "y =", y)
Sample Output
After swapping (tuple unpacking): x = 10 y = 5
The unpacking version finishes with x holding 10 and y holding 5.
In this one
- Preserve a value before reassignment
- Trace a three-assignment swap
- Use simultaneous unpacking
How it works
- 1
Store the old a in temp before changing a.
- 2
Copy b into a, then temp into b, and print both.
- 3
Initialize x and y, evaluate y and x, and unpack them into x and y.
Edge cases
Equal values
Start both variables at 5.
The swap still happens, but the displayed values look unchanged.
Only two sequential assignments
Write a = b followed by b = a.
The second assignment reads the new a, so the original a has already been lost.
What's going on
The temp version is what every language teaches: temp = a, a = b, b = temp. Save the old a before replacing it. Skip that save and both names can end up holding the old b.
For a = 5 and b = 10, temp keeps 5 while a becomes 10. The final assignment gives b that saved 5. Nothing about print does the swap; by then the work is finished.
Python also lets you write x, y = y, x. Conceptually the right-hand values are packed, then unpacked into the left-hand names. Both right-hand values are evaluated before either target changes. That ordering is the trick, not a hidden arithmetic formula. Use this version once you can trace the longer one.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why is temp needed in the first version?
Pick an answer to check it.
Question 2
When are the right-hand values in x, y = y, x read?
Pick an answer to check it.
Questions people ask
Why is temp needed in the first version?
It preserves the old a while a is replaced by b.
When are the right-hand values in x, y = y, x read?
Both are evaluated before the left-hand names receive their new values.
Does unpacking work with strings too?
Yes. Swapping names does not require their values to be numbers.