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.

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Leave a Comment