Understanding Python’s a,b = b,a Variable Swap: Bytecode, Stack Operations, and Evaluation Order
This article explains how Python’s elegant a,b = b,a variable swap works under the hood by examining bytecode, stack manipulation with ROT_TWO, evaluation order nuances, and the differences when swapping more than two variables, providing clear code examples and interpreter insights.
Python programmers are familiar with the concise a,b = b,a syntax for swapping two variables, which avoids the temporary variable required in many other languages.
In C, the same operation typically requires a temporary variable:
int a = 1;
int b = 2;
int temp;
temp = a;
a = b;
b = temp;Python achieves the swap with a single line:
a,b = 1,2
a,b = b,aAlthough the syntax is simple, the underlying mechanism involves bytecode execution, which we explore step by step.
Simple Explanation
The right‑hand side of a,b = b,a is a tuple expression b,a , equivalent to tuple(b, a) . The = performs tuple unpacking, assigning the two elements to the left‑hand variables.
While this description is easy to understand, the actual execution relies on Python’s stack‑based virtual machine.
Bytecode Insight
Python’s interpreter compiles source code to bytecode, which runs on a stack‑based VM. The dis module can decompile bytecode into readable instructions.
>> import dis
>>> dis.dis("a,b=b,a")
0 LOAD_NAME 0 (b)
2 LOAD_NAME 1 (a)
4 ROT_TWO
6 STORE_NAME 1 (a)
8 STORE_NAME 0 (b)
10 LOAD_CONST 0 (None)
12 RETURN_VALUEThe VM pushes b and a onto the stack, then the ROT_TWO instruction swaps the top two stack items. Finally, STORE_NAME pops the values and binds them to a and b .
The stack follows a FILO (first‑in‑last‑out) order, so after pushing b then a , the first pop yields a , then b . Without ROT_TWO , the assignment would incorrectly result in a = a .
Thus, the swap is performed by stacking, rotating, and storing the two values.
Consequently, the common description of “tuple unpacking” is not entirely accurate for this two‑element case.
How the Backend Executes ROT_TWO
In the CPython source file Python/ceval.c , the ROT_TWO operation is defined as:
TARGET(ROT_TWO){
PyObject *top = TOP();
PyObject *second = SECOND();
SET_TOP(second);
SET_SECOND(top);
FAST_DISPATCH();
}The macros TOP and SECOND retrieve the top two stack elements, and SET_TOP / SET_SECOND swap them.
Strange Evaluation‑Order Phenomenon
Consider the following list manipulation:
>> a = [0, 1, 3, 2, 4]
>>> a[a[2]], a[2] = a[2], a[a[2]]
>>> a
[0, 1, 2, 3, 4]
>>> a = [0, 1, 3, 2, 4]
>>> a[2], a[a[2]] = a[a[2]], a[2]
>>> a
[0, 1, 3, 3, 4]The difference arises because Python first evaluates the right‑hand side, storing the values as temporaries, then assigns left‑to‑right. Modifying a[2] first changes the index used for the second assignment.
You can use disassembled code to analyze the exact steps that produce this behavior.
When More Elements Are Involved
For swaps involving more than two elements or constant tuples, Python does not use ROT_TWO . Instead, it builds a tuple and unpacks it:
>> dis.dis("a,b,c,d=b,c,d,a")
0 LOAD_NAME
3 LOAD_NAME
6 LOAD_NAME
9 LOAD_NAME
12 BUILD_TUPLE
15 UNPACK_SEQUENCE
18 STORE_NAME
21 STORE_NAME
24 STORE_NAME
27 STORE_NAME
30 LOAD_CONST
33 RETURN_VALUEThus, for fewer than four elements Python employs optimized stack operations, while larger swaps fall back to tuple construction and unpacking.
Python also supports ROT_THREE and, in newer versions, ROT_FOUR , enabling optimized swaps of three or four items.
>> import opcode
>>> opcode.opmap["ROT_THREE"]
3Summary
We have examined the implementation and runtime behavior of Python’s elegant a,b = b,a swap, explored its bytecode, stack operations, evaluation order, and limitations, and learned how to analyze such constructs using the interpreter’s disassembly tools.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.