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.
- variables
- tuple unpacking
- assignment
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
a = 5
b = 10
print("Before:", a, b)
a, b = b, a
print("After:", a, b)Before: 5 10
After: 10 5How it works
- a and b start as 5 and 10.
- On the right of a, b = b, a Python first builds the tuple (10, 5) from the current values.
- The tuple is then unpacked from left to right: a gets 10 and b gets 5.
- 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.
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.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.