Sometimes, we want to swap two variables in Python.
In this article, we’ll look at how to swap two variables in Python.
How to swap two variables in Python?
To swap two variables in Python, we can a tuple to another tuple.
For instance, we write
(a, b) = (b, a)
to put a
and b
in a tuple with (b, a)
.
Then we unpack the values and assign them to a
and b
.
Conclusion
To swap two variables in Python, we can a tuple to another tuple.