How do you swap two variables in Python without a temporary variable?
Use tuple unpacking: a, b = b, a. The right side is evaluated into a tuple first, then assigned to the names on the left, so no temporary variable is needed.
Explain it simply
Swapping two glasses of water needs a third glass in most languages. Python lets you do it with both hands at once: it first notes down both current values, then pours them back crosswise.
Technically, b, a is built as a tuple of the current values. Then that tuple is unpacked into a and b from left to right.
Example
a, b = 3, 7
a, b = b, a
print(a, b) # Output: 7 3
nums = [10, 20, 30]
nums[0], nums[2] = nums[2], nums[0]
print(nums) # Output: [30, 20, 10]
x, y, z = 1, 2, 3
x, y, z = z, x, y
print(x, y, z) # Output: 3 1 2It works on list elements too, which is how in-place algorithms like bubble sort swap neighbours.
What to say in the interview
"I write a, b = b, a. Python evaluates the whole right-hand side into a tuple before assigning, so the old values are safe. It works for any assignable targets, including list items, and extends to three or more variables."
Common mistakes
- Writing
a = b; b = a, which makes both names the same value.