How to swap two variables in Python

In this post I will show how to swap the values of two variables.

The first way is very common in many languages and require the use of a third variable.

The second and recommended way is what they call pythonic, it uses a Python shorthand to make the swap.

Common way: using a temporary third variable

x = 32
y = 64

print(x)
#output: 32

print(y)
#output: 64

#swapping
temp = x
x = y
y = temp

print(x)
#output: 64

print(y)
#output: 32

This is what you have to do in most programming languages.

You store tha value of x in a third temporary temp, then assign the value of y to x.

Finally, assign the value of temp (which was the previous value of x) to y.

Pythonic and standard way to swap variables

x = 32
y = 64

print(x)
#output: 32

print(y)
#output: 64

#swapping
x, y = y, x

print(x)
#output: 64

print(y)
#output: 32

This tuple syntax is the standard way to swap variables in Python.

The first variable in the left side x receives the value of the first variable in the right side y.

The same applies to the second variable in the left side y receiving the value of the second variable in the right side x.