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.

Please help us and share this article

About the author

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He's been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python!

Leave a Comment