PythonMastery

Swap two variables in Python

Swap the values of two variables with a, b = b, a. How the one-line swap works, and the temporary-variable version other languages use.

Python can swap two values in one line, without a third variable.

The program

python
a = 10
b = 20

a, b = b, a

print(f"a = {a}, b = {b}")
output
a = 20, b = 10

How it works

The long way

In many other languages you need a temporary variable. This also works in Python, but it takes three lines:

python
a = 10
b = 20

temp = a
a = b
b = temp

print(f"a = {a}, b = {b}")
output
a = 20, b = 10

Learn the idea: Variables & Data Types, Tuples: Lists That Can't Be Changed