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.

About Erik van Baaren

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! Writing good articles takes time and effort. Did you like this tutorial? You can buy him a coffee to show your appreciation.

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments

No, thanks!