How to Swap Two Variables in Python

· 1 min read · Updated March 16, 2026 · beginner
python variables basics

Swapping two variables is a common operation. Python makes it elegant.

Using Tuple Unpacking

The Pythonic way to swap variables:

a = 1
b = 2

a, b = b, a

print(a)  # 2
print(b)  # 1

This is the recommended approach. It is clean, readable, and efficient.

Using a Temporary Variable

The classic approach works too:

a = 1
b = 2

temp = a
a = b
b = temp

print(a)  # 2
print(b)  # 1

This is useful when you need to do more complex operations during the swap.

Swapping Multiple Values

Tuple unpacking shines with multiple values:

a = 1
b = 2
c = 3

a, b, c = c, a, b

print(a, b, c)  # 3 1 2

When to Use What

  • Tuple unpacking: Use for simple swaps. It is idiomatic Python.
  • Temporary variable: Use when you need operations during the swap.

See Also