Swap Two Numbers Without Using a Third Variable

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.

Share this

Leave a Comment