Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you swap two variables in Python without a temporary variable?

SHORT ANSWER

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

python
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 2

It 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.

#python#variables

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.