With this neat little trick, you can swap two Python variables without using a third variable:
a = 1
b = 2
a, b = b, a
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
Our premium courses offer a superior user experience with small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.
This article is part of the free Python tutorial. You can head over to the start of the tutorial here.
You can navigate this tutorial using the buttons at the top and bottom of the articles.
To get an overview of all articles in the tutorial, please use the fold-out menu at the top.
If you liked this article, you might also like to read the following articles: