Reading Time: 1 minutes
Variable Swapping in Python
Variable Swapping in Python: Python makes it really easy to swap values of two or more variables. Example:
>>> x = 10 |
>>> y = 20 |
>>> x, y = y, x |
>>> y |
10 |
>>> x |
20 |
>>> x = 1 |
>>> y = 2 |
>>> z = 3 |
>>> z, y, x = x, y, z |
>>> z |
1 |
>>> y |
2 |
>>> x |
3 |
The way this works is that the expression on the right hand side creates a new tuple. This is one of the ways that tuples can be created. The tuple thus formed gets unpacked into variables on the left hand side.