Swapping two variables with a, b = b, a works because the right-hand side is fully evaluated into a temporary tuple before any assignment happens. Python builds the tuple (b, a) from the current values, then unpacks it left-to-right into a and b, so the original values are never lost. This is the same mechanism behind the common tuple-swap idiom a, b = b, a — and it generalises to any number of names, including the pattern a, b, b, a when you deliberately repeat names on the left.
Background: Tuples and Multiple Assignment
A tuple is an immutable ordered sequence. In Python, a comma creates a tuple even without parentheses, so b, a is a tuple literal. Multiple assignment (also called iterable unpacking) lets you bind several names at once: x, y = 1, 2. The left side is a target list; the right side is any iterable with the right number of items.
Before the tuple-swap idiom became idiomatic, programmers used a temporary variable:
temp = aa = bb = temp
The tuple form removes the temporary variable from your source code, but internally an equivalent temporary still exists — the tuple itself. The key rule is evaluation order: Python evaluates the entire right-hand side first, then performs assignments left to right. That is why a, b = b, a is safe even though a is overwritten before b is assigned.
How the Swap Works Internally
Consider a = 1; b = 2; a, b = b, a. The interpreter roughly does this:
- Evaluate
b→ 2. - Evaluate
a→ 1. - Build the tuple
(2, 1). - Unpack the tuple: assign 2 to
a, then 1 tob.
At no point does the assignment to a affect the value that will be assigned to b, because b's new value was already captured in the tuple. This is not a special “swap opcode”; it is ordinary tuple construction plus unpacking. In CPython, the compiler emits BUILD_TUPLE (or a specialised variant) followed by UNPACK_SEQUENCE and STORE_NAME/STORE_FAST instructions. The tuple is a real object, though short-lived and usually freed immediately after unpacking.
The same logic applies when the right side is not a tuple literal but any iterable of matching length, such as a, b = [b, a] or a, b = some_function_returning_two_values(). If the iterable yields too many or too few items, Python raises ValueError before any assignment occurs — another consequence of “evaluate first, assign second.”
What About a, b, b, a?
The pattern a, b, b, a is not a standard swap. On the right-hand side, a, b, b, a builds a four-element tuple from the current values. On the left-hand side, the same four names are targets. Python assigns left to right, so the last assignment to each name wins. For example, with a = 1; b = 2, a, b, b, a = 1, 2, 2, 1 assigns 1 to a, 2 to b, 2 to b again, then 1 to a again — net result unchanged. If you write a, b, b, a = b, a, a, b, the final values are whatever the last assignment to each name produced: a gets the fourth element, b gets the third. This is legal but confusing; it is not a rotation or a double swap.
If you want to rotate three or more values, use distinct names on the left, e.g. a, b, c = b, c, a. Repeating a target name is almost always a mistake unless you are deliberately discarding earlier assignments.
Common Problems and Misconceptions
- “It swaps in place without a temporary.” It avoids a named temporary in your code, but the tuple is a temporary object. The memory saving is negligible; the readability gain is real.
- “It works for any iterable of any length.” Only if the lengths match exactly.
a, b = [1, 2, 3]raisesValueError: too many values to unpack. - “Order of assignment doesn't matter.” It does when target names repeat. With distinct names, left-to-right assignment is invisible; with repeats, it determines the result.
- “Swapping mutable objects swaps their contents.” No — it swaps references. If
aandbpoint to lists, after the swap the names point to different list objects; the lists themselves are untouched. - “The right side must be a tuple.” Any iterable of the right length works, including generators, ranges and strings.
Alternatives and Comparisons
There are several ways to exchange two values, each with trade-offs:
- Tuple unpacking:
a, b = b, a— concise, idiomatic, evaluates both sides once. - Temporary variable: three statements, explicit, works in almost every language.
- Arithmetic trick:
a = a + b; b = a - b; a = a - b— fails for non-numeric types and can overflow in fixed-width languages; not recommended in Python. - XOR trick:
a ^= b; b ^= a; a ^= b— works only for integers and is harder to read. - List assignment:
lst[i], lst[j] = lst[j], lst[i]— the same unpacking mechanism applied to subscripts; both index expressions are evaluated before assignment.
For swapping elements inside a list, the subscript form is the standard approach and avoids the pitfalls of manual index juggling. For swapping attributes, obj.x, obj.y = obj.y, obj.x works the same way, provided the attribute lookups are side-effect free.
Safety and Edge Cases
The tuple-swap idiom is safe for ordinary names and attributes, but a few edge cases deserve attention. If the right-hand side contains function calls, those calls happen before any assignment, so exceptions abort the swap cleanly. If the left side contains subscripts with side effects, evaluation order matters: Python evaluates the target list left to right during assignment, which can produce surprising results if the same object is indexed twice. For example, lst[0], lst[0] = 1, 2 leaves lst[0] equal to 2, because the second assignment overwrites the first.
Thread safety is another consideration. A tuple swap is not atomic in the sense of a single machine instruction; another thread could observe intermediate state between the two stores. In multithreaded code, protect shared swaps with a lock if consistency matters. For local variables in a single thread, no such concern exists.
Finally, beware of swapping names that are not yet bound. a, b = b, a raises NameError if either name is undefined, because the right side is evaluated first.
Frequently Asked Questions
Does a, b = b, a create a temporary tuple?
Yes. The right-hand side is evaluated into a tuple object before assignment. The tuple is usually short-lived and reclaimed immediately, but it is a real object, not a compiler-level register swap.
Why does a, b = b, a work when a = b; b = a does not?
In a = b; b = a, the first statement overwrites a with b's value, so the second statement assigns b to itself. The tuple form captures both original values before any assignment.
Can I swap more than two values at once?
Yes, as long as the number of targets matches the number of values: a, b, c = c, a, b rotates three values. The same evaluate-then-assign rule applies.
What happens if I repeat a name on the left, like a, b, b, a?
Python assigns left to right, so the last assignment to each name determines its final value. Repeating names is legal but rarely what you want; it is not a double swap.
Is tuple swapping faster than using a temporary variable?
The difference is usually negligible. The tuple form is more readable and avoids a named temporary, but both approaches perform a small, constant amount of work. Choose based on clarity, not micro-optimisation.
Does swapping work with list elements?
Yes: lst[i], lst[j] = lst[j], lst[i] uses the same unpacking mechanism. Both index expressions are evaluated before assignment, so the swap is correct even when i and j refer to the same position.