Home / Python / Example programs / Basics

Python program: Swap two variables

Exchange the values of two variables.

The code

x = 5
y = 10
print("before:", x, y)

x, y = y, x          # Python's tuple swap
print("after: ", x, y)

# the classic way, with a temporary variable
temp = x
x = y
y = temp
print("back:  ", x, y)

Output

before: 5 10
after:  10 5
back:   5 10

How it works

x, y = y, x builds the pair (10, 5) on the right first, then unpacks it into x and y. Many languages need a temporary variable; Python does not.

Python features used

Learn the ideas behind it in the free lesson Lists & Tuples.