In programming, there are times when you want to swap the values stored in two variables. For example, when implementing sorting algorithms.
Traditional Method (Using a Temporary Variable)
In many programming languages, you need a third temporary variable (often called temp or tmp) to swap the values of two variables.
width = 800
height = 600
print(f"Before: Width={width}, Height={height}")
# 1. Save width value to temp variable
temp = width
# 2. Assign height value to width
width = height
# 3. Assign the saved temp (original width) value to height
height = temp
print(f"After: Width={width}, Height={height}")
Output:
Before: Width=800, Height=600
After: Width=600, Height=800
This method works reliably, but it requires three lines of code and an extra variable, making it slightly verbose.
The Pythonic Solution (Multiple Assignment)
Python provides a syntax to write this swap in a single line, intuitively, without using a temporary variable. This uses a feature called “Multiple Assignment” or “Tuple Unpacking”.
Syntax:
var1, var2 = var2, var1
Example: Here is how you write the swap for width and height in Python.
width = 800
height = 600
print(f"Before: Width={width}, Height={height}")
# Swap in one line using Python syntax
width, height = height, width
print(f"After: Width={width}, Height={height}")
Output:
Before: Width=800, Height=600
After: Width=600, Height=800
We achieved the exact same result as using the temp variable, but in just one line.
Why is this Possible?
The code width, height = height, width works internally as follows:
- First, the right side
(height, width)is evaluated. At this point, a tuple(600, 800)is temporarily created in memory. - Next, that tuple is unpacked and assigned to the variables
widthandheighton the left side. - As a result,
widthgets600andheightgets800simultaneously.
Since the right side is evaluated before the assignment to the left side occurs, the values are not overwritten or lost, even without a temporary variable.
Swapping Three or More Variables
You can apply this syntax to swap three or more variables simultaneously (like a rotation).
a = 10
b = 20
c = 30
print(f"Before: a={a}, b={b}, c={c}")
# Rotate: a -> b, b -> c, c -> a
a, b, c = b, c, a
print(f"After: a={a}, b={b}, c={c}")
Output:
Before: a=10, b=20, c=30
After: a=20, b=30, c=10
Summary
- In Python, while the traditional method using a
tempvariable works, it is not recommended. - By using the multiple assignment syntax
a, b = b, a, you can write concise and efficient code in a single line.
