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 right side,
b, a, is evaluated first. It makes a pair of the two current values:(20, 10). - The left side,
a, b, then unpacks that pair:agets the first value andbgets the second. - Because the pair is built before anything is assigned, neither value is lost.
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