Swap Two Python Variables Without Using a Third One

With this neat little trick, you can swap two Python variables without using a third variable:

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

It’s just one line of code! As you can see in line 3, no temporary variable is needed to swap variables in Python.

Why this works

Line 3 does two things. First, Python evaluates the right side, b, a. A comma-separated list of values creates a tuple, so the right side becomes the tuple (2, 1). This is called tuple packing. Then Python assigns the values in that tuple to the names on the left side, one by one: a gets 2 and b gets 1. That’s called tuple unpacking, or multiple assignment.

Because the whole right side is evaluated before anything is assigned, the old value of a is still available when it’s needed. Strictly speaking, Python does use temporary storage behind the scenes; you just don’t have to write it yourself.

The same trick works with more than two variables, and with items in a list:

x, y, z = 1, 2, 3
x, y, z = z, x, y
print(x, y, z)
# 3 1 2

numbers = [10, 20, 30]
numbers[0], numbers[2] = numbers[2], numbers[0]
print(numbers)
# [30, 20, 10]

Leave a Comment