Python Practice › Basic Programs › Program 8
Swap two variables
Write a Python program to interchange (swap) the values of two variables.
Input
a = 10, b = 20
Output
a = 20 b = 10
Approach
- Use tuple unpacking
a, b = b, a, or a temporary variable.
Solution 1: tuple unpacking
a = 10b = 20 a, b = b, aprint("a =", a)print("b =", b)Output
a = 20 b = 10
Line by line
Line 4
The right side b, a is evaluated first as the tuple (20, 10) and then unpacked into a and b, so no temporary variable is needed.
Solution 2: temporary variable
a = 10b = 20 temp = aa = bb = tempprint("a =", a, "b =", b)Output
a = 20 b = 10
Line by line
Lines 4-6
temp keeps the old value of a before it is overwritten. This is how swapping works in most other languages.
Learn the concept
New to this topic? Read the lesson, then come back.