You’ve been using a temporary variable to swap values for years. It works, but Python has a more elegant one-liner that reads like plain English — and it’s faster too. Here’s the complete guide to tuple unpacking for variable swapping.
In this tutorial, you will learn to:
- Swap two variables using tuple unpacking in a single line
- Swap three or more variables without temporary storage
- Understand when XOR swap works and why it fails on floats
- Avoid common pitfalls in Python variable swapping
Page Contents
The Problem with Temporary Variables
Swapping two variables is one of the most common operations in programming. The traditional approach uses a temporary variable to hold one value during the swap:
# The old way — works, but feels clunky
a = 5
b = 9
temp = a
a = b
b = temp
print(f"After swap: a={a}, b={b}") # a=9, b=5
It works. But you need a third variable, three assignment statements, and the mental overhead of tracking which value is where at each step. Python offers a cleaner path.
Tuple Unpacking Swap — The Pythonic Way
Python’s tuple unpacking lets you swap variables in a single line. The right side creates a tuple (b, a), and the left side unpacks it into a, b — simultaneously. No intermediate variable needed.
a, b = 5, 9
print(f"Before: a={a}, b={b}")
a, b = b, a # Single line swap
print(f"After: a={a}, b={b}")
Output
Before: a=5, b=9
After: a=9, b=5
No temporary variable. The swap reads like a sentence: a becomes b, and b becomes a. Python evaluates the right side fully before assigning anything — so both variables swap in one atomic step.
How the Swap Works — Visual Breakdown
Before: After:
┌─────────────────┐ ┌─────────────────┐
│ a = 5 │ │ a = 9 │
│ b = 9 │──►│ b = 5 │
└─────────────────┘ └─────────────────┘
Step 1: (b, a) creates tuple (9, 5)
Step 2: (a, b) = (9, 5) unpacks simultaneously — not sequentially
Critical point: Python evaluates the entire right-hand side (b, a) before touching any variable on the left. This means you don’t need a temporary variable to preserve a value — it’s safe to overwrite both sides simultaneously.
The XOR Swap — Educational Curiosity
Another trick from low-level programming is the XOR swap. It uses bitwise XOR operations to swap values without any temporary storage — relying on the fact that a ^ a = 0 and a ^ 0 = a:
x, y = 42, 17
print(f"XOR swap — Before: x={x}, y={y}")
x = x ^ y # x = 42 ^ 17 = 47
y = x ^ y # y = 47 ^ 17 = 42
x = x ^ y # x = 47 ^ 42 = 17
print(f"After: x={x}, y={y}")
Output
XOR swap — Before: x=42, y=17
After: x=17, y=42
Important limitation: XOR swap only works on integers. It fails on floats — attempting 3.14 ^ 2.71 raises a TypeError because XOR is defined only for integer types. For Python, this makes tuple unpacking the universal choice.
Note: The XOR swap is academic in Python. It matters in C and embedded systems where registers are scarce. In Python, tuple unpacking is clearer, works on all types, and is just as fast — the interpreter optimizes it at the C level.
Swapping Three or More Variables
Tuple unpacking extends naturally to more than two variables. You can rotate any number of values in a single line:
# Rotate three variables — a→b, b→c, c→a
a, b, c = 1, 2, 3
print(f"Before: a={a}, b={b}, c={c}")
a, b, c = c, a, b
print(f"After: a={a}, b={b}, c={c}")
Output
Before: a=1, b=2, c=3
After: a=3, b=1, c=2
The rotation is simultaneous — no temporary storage needed regardless of how many variables you’re working with. You can also reverse direction cleanly:
# Reverse four values
w, x, y, z = 'a', 'b', 'c', 'd'
w, x, y, z = z, y, x, w
print(f"Reversed: w={w}, x={x}, y={y}, z={z}") # w='d', x='c', y='b', z='a'
Edge Cases
Swapping the Same Variable
What if both variables hold the same value? Tuple unpacking handles it gracefully — no special case needed:
p, q = 7, 7
print(f"Same value — Before: p={p}, q={q}")
p, q = q, p
print(f"After: p={p}, q={q}") # Still works — no error
Different Types
Tuple unpacking works across types — strings, lists, objects, anything. Python doesn’t care what types you’re swapping:
name, score = "Alice", [95, 87, 91]
name, score = score, name
print(f"Name: {name}, Score: {score}") # name=[95, 87, 91], score="Alice"
Common Mistakes / Gotchas
- Unpacking with mismatched counts:
a, b = 1, 2, 3raisesValueError: too many values to unpack. Ensure the left and right sides have the same number of elements. - Mutable objects: Swapping two variables that reference the same mutable object does not create a copy. After
a, b = b, a, both still point to the same object — but the references themselves are swapped, not the object contents. - Chain assignment confusion:
a = b = 5assigns the same object to both names. Swapping afterward works correctly, but beginners sometimes expecta = b = 5; a, b = b, ato produce different values — it won’t.
Why Tuple Unpacking Wins
- Readability:
a, b = b, aexpresses intent directly — two values trading places - No temp variable: Fewer lines, fewer named variables to track
- Pythonic: Matches how Python handles multiple return values and
*argsunpacking - Works on all types: Integers, floats, strings, lists, custom objects — anything
- Performance: Tuple creation and unpacking are optimized at the C level in CPython — the overhead is negligible compared to the assignment overhead in any language
Summary & Next Steps
Python’s tuple unpacking makes variable swapping a one-liner that’s clearer and as fast as any manual approach. The key insight is that Python evaluates the entire right side before assigning anything — so simultaneous swaps work without temporary storage.
Next time you need to swap two values, skip the temp variable. Just write a, b = b, a — Python handles the rest.
To go deeper into Python’s handling of multiple values and arguments, see these related guides:
- Python Functions: The Complete Guide — covers multiple return values,
*args, and**kwargs - Python Tuples and Tuple Methods: The Complete Guide — the data structure behind unpacking
- Python Docs: Tuples and Sequences — official documentation on tuple unpacking

