Skip to content
Devtoolry

Basics · beginner

Python Program to Swap Two Variables

Swap the values of two variables in Python with tuple unpacking (a, b = b, a), and see the temporary-variable method other languages use.

Swapping two values is a building block of sorting algorithms and many puzzles. In C or Java you need a third, temporary variable. Python can do it in one line because the right-hand side of an assignment is evaluated completely before anything is assigned.

The program

Python
a = 5
b = 10
print("Before:", a, b)

a, b = b, a
print("After:", a, b)
Output
Before: 5 10
After: 10 5

How it works

  1. a and b start as 5 and 10.
  2. On the right of a, b = b, a Python first builds the tuple (10, 5) from the current values.
  3. The tuple is then unpacked from left to right: a gets 10 and b gets 5.
  4. Because the tuple was built first, neither value is lost, so no temporary variable is needed.

Watch it run line by line

Watch the swap line: a and b change together in one step. In the temporary-variable version below you can see the extra variable temp hold the old value of a for one step.

“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: With a temporary variable

This is how the swap works in most other languages. It is longer, but it shows exactly what happens and is useful when you translate code.

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

Common mistakes

  • Writing a = b and then b = a: after the first line both variables hold 10, so the original 5 is lost.
  • The arithmetic trick a = a + b; b = a - b; a = a - b only works for numbers and is harder to read. Tuple unpacking works for any values.

Try it yourself

  • Rotate three variables: make a, b, c = 1, 2, 3 become 2, 3, 1 in one line.
  • Swap the first and last items of a list with the same trick: items[0], items[-1] = items[-1], items[0].

Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 Python examples, or write your own program in the online Python Compiler.