Swapping variables
- Python course
- Beginner
- Lesson 11/116
- 4 min
Learn to swap values with a, b = b, a.
Swapping variables
Exchanging the values of two variables is called a swap. In Python a swap is very easy:
a, b = b, aThe right side is evaluated first: a (b, a) tuple is built. Then the left side unpacks it. So no temporary variable is needed.
In other languages a temporary variable is usually needed. Python's multiple assignment does it in one line.
Swap with a temporary variable
In some languages a swap uses a temporary variable. It can be done in Python too, but it is not needed:
temp = a
a = b
b = tempThis method is longer and error-prone (it is easy to mix up the order). Python's a, b = b, a is both shorter and safe because it happens at once.
Practice Swap and print
Assign a = 1 and b = 2. Then swap them with a, b = b, a. Finally print print(a, b).
Starter code
# Define a and bSample solution
a = 1
b = 2
a, b = b, a
print(a, b)Expected output
2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Swap a and b
a, b = ____
a, b = b, a
Explanation: a, b = b, a performs the swap.
2 Which is the easiest swap in Python?
- swap(a, b)
- temp = a; a = b; b = temp
- a = a + b; b = a - b; a = a - b
- a, b = b, a Correct answer
Explanation: a, b = b, a is the easiest way to swap in Python.
3 Match the swap methods
| Term | Meaning |
|---|---|
a, b = b, a |
Python way |
temp = a; a = b; b = temp |
Temporary variable |
a, b = 1, 2 |
Multiple assignment |
type(a) |
Type check |