Swap Two Variables in Python
The textbook temp-variable swap, then the one-liner you will actually use.
BeginnerBasic Python ProgramsExample 3 of 25
swap-two-variables.py
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)
Output
After swapping (using temp): a = 10 b = 5 After swapping (tuple unpacking): x = 10 y = 5
In this one
- temp swap: three lines, easy to mess up
- x, y = y, x is the Python version
What's going on
The temp version is what every language teaches:
temp = a → a = b → b = temp
Miss a step and both variables hold the same value. I have done that in interviews.
Python also lets you write x, y = y, x. Right-hand side is packed into a tuple first, then unpacked. No temp. That is the one you keep.
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.