Python programs / Numbers / Swap two numbers

Python Program to Swap Two Numbers

Beginner Numbers

Swaps the values of two variables in one line with a, b = b, a, without a temporary variable.

Swapping exchanges the values of two variables: if a is 5 and b is 10, afterwards a is 10 and b is 5. The first idea, a = b and then b = a, doesn't work: the first line overwrites the 5, so both end up 10. Python can swap in one line, a, b = b, a, with no third variable to keep a value safe on the way.

Program

a = 5
b = 10
print(f"Before: a = {a}, b = {b}")

a, b = b, a
print(f"After: a = {a}, b = {b}")

Open in the editor Download swap_numbers.py

Output

Before: a = 5, b = 10
After: a = 10, b = 5

How it works

  1. a holds 5 and b holds 10.
  2. The program prints them before the swap.
  3. The swap. Python works out the right-hand side first: b, a makes a tuple of the two current values, (10, 5). Only then does it unpack that tuple into the names on the left, a and b, in order. Both values were read before either variable changed, so nothing is lost.
  4. Now a is 10 and b is 5.

Other ways to write it

With a temporary variable

Most other languages, such as C and Java, swap with a third variable that keeps the first value while it's overwritten:

a = 5
b = 10
temp = a
a = b
b = temp
print(a, b)

With arithmetic

An exam favourite swaps two numbers without a third variable by adding and subtracting. It works only for numbers, and is harder to read than a, b = b, a.

a = 5
b = 10
a = a + b  # 15
b = a - b  # 15 - 10 = 5
a = a - b  # 15 - 5 = 10
print(a, b)

Try it yourself

  • Try the first idea, a = b and then b = a, and print both: they're both 10.
  • Swap two strings, such as "left" and "right": the one-line swap works for any values.
  • Rotate three variables with a, b, c = b, c, a.
  • Swap the first and last items of a list with items[0], items[-1] = items[-1], items[0], as sorting programs do.

More numbers programs

Share this program