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 variable
2a = 5
3b = 10
4
5temp = a
6a = b
7b = temp
8
9print("After swapping (using temp): a =", a, "b =", b)
10
11# Swapping using Python tuple unpacking
12x = 5
13y = 10
14
15x, y = y, x
16
17print("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.