Swap Two Variables in Python: All Four Methods
Four ways to swap two variables in Python: tuple unpacking, temp variable, arithmetic, and XOR, with code examples, derivations, and placement test context.
Python’s a, b = b, a swaps two variables in one line with no temporary variable, no arithmetic tricks, and no type restrictions.
That single statement is the idiomatic answer in production code. But placement coding rounds at service companies still ask candidates to demonstrate a swap without a temp variable using arithmetic or bitwise logic. This article covers four methods, derives the math, and flags the edge cases interviewers care about.
The one-line swap Python was built for
Tuple unpacking is the canonical swap in Python:
a = 10
b = 20
a, b = b, a
print(a) # 20
print(b) # 10
How it works: the Python language reference specifies that the right-hand side of an assignment is evaluated fully before any binding on the left side begins. So b, a builds an intermediate tuple (20, 10) on the stack, then unpacks it into a and b respectively.
This works for any type: integers, floats, strings, lists. It extends to three or more variables (a, b, c = c, a, b). In CPython’s bytecode, a two-variable swap compiles down to a single ROT_TWO instruction that pointer-swaps the top two stack values, making it as fast as any C-level temp swap.
If you are working through a Python basic programs guide, tuple unpacking is the first idiom to internalise.
Swapping with a temporary variable
The temp variable approach is what most students learn first:
a = 10
b = 20
temp = a
a = b
b = temp
print(a) # 20
print(b) # 10
Three statements, zero ambiguity. Each step does exactly one thing:
temp = asaves the original value ofaa = boverwritesawith the value ofbb = tempwrites the saved original intob
This method has no type restriction and no precision risk. It is the safest approach to explain during an interview because an interviewer can trace each line without mental overhead. The logic is identical to the intermediate step in finding the greatest of two numbers in Python where you hold one value aside while comparing the other.
Arithmetic swap: how the math works
The addition-subtraction swap eliminates the temp variable:
a = 5
b = 3
a = a + b # a = 8
b = a - b # b = 8 - 3 = 5 (original a)
a = a - b # a = 8 - 5 = 3 (original b)
print(a) # 3
print(b) # 5
Derivation
- Let original values be A and B.
- After step 1:
aholds A + B. - After step 2:
b= (A + B) - B = A. - After step 3:
a= (A + B) - A = B.
Python-specific notes
- Python integers have arbitrary precision. There is no 32-bit signed overflow. The arithmetic swap is safe for any integer size in Python, unlike C or Java where large values can overflow.
- For floats, IEEE 754 rounding errors mean
(a + b) - bmay not exactly equal the originala. Do not use this method with floats in production.
The same operator logic you use here appears in the calculator program in Python where addition and subtraction are chained across user inputs.
XOR swap: bitwise and integers only
The XOR approach uses the ^ operator:
a = 10
b = 20
a = a ^ b # a = 30 (binary: 11110)
b = a ^ b # b = 30 ^ 20 = 10 (original a)
a = a ^ b # a = 30 ^ 10 = 20 (original b)
print(a) # 20
print(b) # 10
Binary verification
a= 10 =01010,b= 20 =10100- Step 1:
01010 XOR 10100=11110(30) - Step 2:
11110 XOR 10100=01010(10) - Step 3:
11110 XOR 01010=10100(20)
The algebraic identity behind this is: (A XOR B) XOR B = A, because XOR is its own inverse. The Python docs on bitwise operations confirm that ^ performs bitwise exclusive OR on integers.
The aliasing trap (C-specific, not Python)
In C, if two pointers point to the same memory address and you XOR-swap through them, both values zero out. Python does not have this problem. a ^= b rebinds the name a to a new integer object without mutating the object b references. Even when a == b, the three steps resolve correctly:
a = 5 ^ 5= 0b = 0 ^ 5= 5a = 0 ^ 5= 5
Result: both remain 5. No data loss.
Limitations
- Works on integers only. Floats, strings, and lists have no XOR operator.
- No speed advantage over tuple unpacking in CPython.
- Harder to read than the tuple idiom or the temp variable.
Which method to use: a comparison
| Method | Works on floats | Works on strings | No temp variable | Typical placement context |
|---|---|---|---|---|
| Tuple unpacking | Yes | Yes | Yes | Production Python, quick demos |
| Temp variable | Yes | Yes | No | Explaining logic step by step |
| Arithmetic (+/-) | Imprecise | No | Yes | ”Swap without temp” interview question |
| XOR | No | No | Yes | Bitwise logic follow-up question |
For placement coding tests: know tuple unpacking as your default answer. Be ready to demonstrate arithmetic swap when the interviewer says “now do it without a temp variable.” Mention XOR only if asked about bitwise operations.
After the placement round
The arithmetic and XOR methods test whether you can trace state through a sequence of mutations. That same skill (tracking how data transforms step by step) is what building with LLMs requires: you feed a prompt, observe the output, adjust parameters, and re-run. TinkerLLM is a self-paced playground where you do exactly that, starting at ₹299. If the tuple idiom is your Python instinct, TinkerLLM is where you build that same instinct for prompt engineering.
Primary sources
Frequently asked questions
Does a, b = b, a actually use a temporary variable internally?
Yes. CPython evaluates the right side first, builds an intermediate tuple on the stack, then unpacks it into the left-side names. The tuple is the implicit temp. At the bytecode level the operation is ROT_TWO, which is a single-instruction pointer swap on the value stack.
Does the arithmetic swap work with Python floats?
Technically yes, but floating-point rounding can corrupt the result. For example, swapping 0.1 and 0.2 may not round-trip perfectly because IEEE 754 addition is not exact. Use tuple unpacking for floats.
Does XOR swap fail when both variables hold the same value?
No. In Python, a ^= b rebinds the name to a new object without touching the object b references. Even when a == b, the three XOR steps resolve correctly (both end at their original values). The aliasing trap exists only in C when two pointers address the same memory location.
Which swap method do placement coding tests expect?
Most placement rounds accept any correct method, but interviewers at service companies like TCS or Infosys often ask candidates to demonstrate swapping without a temp variable. Know the arithmetic method and the tuple idiom, and mention that XOR exists.
Can you swap more than two variables at once with tuple unpacking?
Yes. Python allows a, b, c = c, a, b to rotate three variables in a single statement. The right side is evaluated fully before any assignment on the left side begins.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)