Introduction
Swapping variables is a fundamental operation in programming, often needed when reorganizing data, rotating values, or implementing algorithms. Python makes this process exceptionally clean and efficient through tuple unpacking, eliminating the need for manual temporary variables and reducing the risk of mistakes.
The Pythonic Way to Swap Two Variables
Python lets you swap variables in one line without needing a temporary variable:
1 | a, b = b, a |
This uses tuple packing and unpacking, making the swap safe, efficient, and easy to read.
Example
1 2 3 4 5 6 | a = 5 b = 10 a, b = b, a print(a, b) # Output: 10 5 |
The Classic Way (Using a Temporary Variable)
You can still use the traditional method:
1 2 3 | temp = a a = b b = temp |
This works but is less clean and, in most cases, slower than tuple unpacking.
Performance Comparison (Tuple Swap vs Temp Variable)
Using Python's timeit, we compared 10 million swaps:
- Tuple unpacking: ~0.229 s
- Temp variable method: ~0.253 s
Tuple swapping is slightly faster and more Pythonic.
Swapping MORE Than Two Variables
Python doesn't limit you to just two variables — you can swap or rotate any number.
Example: Rotating 3 Variables
1 2 3 4 5 | a, b, c = 1, 2, 3 a, b, c = b, c, a print(a, b, c) # Output: 2 3 1 |
Example: Swapping 4 Variables
1 | x, y, z, w = w, x, y, z |
This rotates all four values forward.
Python handles the right-hand side as a tuple, so no values are ever overwritten during the swap.
How Python Swaps Variables Internally
For the line:
1 | a, b, c = b, c, a |
Python does this under the hood:
Create a temporary tuple from RHS
1 2 | temp_tuple = (b, c, a) # e.g., (2, 3, 1) |
Unpack into the LHS variables
1 2 3 | a = temp_tuple[0] b = temp_tuple[1] c = temp_tuple[2] |
Discard the temporary tuple
1 | Python automatically cleans it up. |
This makes tuple swapping atomic, safe, and elegant.
Conclusion (Best Practice)
For nearly all Python code:
Use this:
1 | a, b = b, a |
Avoid this unless required:
1 2 3 | temp = a a = b b = temp |
Tuple unpacking is:
- Faster
- Cleaner
- Idiomatic Python
- Works on unlimited variables
- Safe for mutable and immutable objects
References
| Links | Site |
|---|---|
| Python Official Tutorial – More on Lists | Python.org |
| Assignment Statements (Tuple Unpacking) | Python.org |
| Data Model – Objects, Values, and Types | Python.org |
