How to Swap Variables in Python with Tuple Unpacking
Learn how to swap variables in Python with tuple unpacking, including evaluation order, list swaps, edge cases, and when a temporary variable is still useful.

Swapping two variables in Python is a one-liner with tuple unpacking:
a, b = b, aThe statement works because Python evaluates the entire right-hand side before any assignment takes place. b, a creates a tuple from the current values of those variables, and the left-hand side unpacks that tuple back into a and b. Unlike C or Java, a simple swap does not need a temporary variable. This article covers the evaluation order, how the pattern extends to lists and function return values, and when a temporary variable is still reasonable.
How Tuple Unpacking Evaluates the Right Side
The key to a, b = b, a is evaluation order. Python evaluates the right-hand side first to produce the tuple (old_b, old_a), then assigns those values to the left-hand targets from left to right. If a = 1 and b = 2, then b, a evaluates to (2, 1), and the assignment makes a become 2 and b become 1. The right side is captured before any variable on the left is overwritten.
Swapping More Than Two Variables
The same mechanism extends to more than two variables. For example, to rotate three values:
a, b, c = c, a, bIf a = 1, b = 2, c = 3, the right side evaluates to (3, 1, 2), so after the assignment a is 3, b is 1, and c is 2. The syntax works for any number of variables, but readability drops as the number grows. For more than three or four values, consider a list, tuple, or another data structure instead of a long rotation.
Swapping Elements in a List
Tuple unpacking also works with subscript targets:
items = [10, 20, 30, 40]
items[1], items[3] = items[3], items[1]After this, items is [10, 40, 30, 20]. The right-hand side reads the current values at indices 1 and 3 before either assignment happens, so the swap does not need a temporary item variable. This is a convenient pattern when reordering list elements in place, for example in a sorting or partition step.
Performance and Memory Characteristics
Tuple unpacking avoids a named temporary variable, but it does create a tuple for the right-hand side. In CPython that tuple is allocated on the heap and soon discarded. For typical code, this overhead is negligible; the swap is O(1) in time and extra memory. Micro-optimizing this line is rarely useful. If profiling identifies this statement as a bottleneck in a hot loop, test alternatives with your interpreter and data before changing readable code for a possible speed gain.
Common Mistakes and Edge Cases
One common mistake is treating a, b = b, a as if it were a = b; b = a. The latter loses the original value of a; tuple unpacking avoids that by reading both values first.
A self-swap such as a, a = a, a is harmless and leaves a unchanged.
When swapping list elements, remember that the right-hand side is evaluated before assignments begin. In common cases like items[i], items[j] = items[j], items[i], this means the original values are read first and the swap is safe. If an index is itself computed from list contents, keep the expression simple or compute the index before the swap to avoid confusion.
When a Temporary Variable Still Makes Sense
The tuple unpacking form is idiomatic for simple swaps, but a temporary variable can be clearer when the values being exchanged come from complex expressions or when the swap is part of a longer algorithm that is easier to follow with a named intermediate. For example:
temp = a
a = b
b = tempThis version makes each step visible, which can aid readability in code where the exchange is not the main point. In general, prefer tuple unpacking for simple variable swaps. Reserve the temporary variable for cases where it genuinely improves clarity, and do not choose one over the other for performance without profiling.
Swapping Values Returned by a Function
Tuple unpacking also applies to function return values. If a function returns two values, you can unpack and then swap them:
def get_coordinates():
return 10, 20
x, y = get_coordinates()
x, y = y, xThis is just another use of the same assignment behavior. It is handy when you need to reorder data returned by an API or computation before using it.
Readability and Maintainability
The main advantage of a, b = b, a is that it expresses the swap directly. A reader does not have to track a temporary variable or inspect multi-line assignment logic. The syntax also matches Python's broader multiple-assignment style, so it fits naturally into existing code. When reviewing code that contains this pattern, you can quickly see that values are being exchanged without checking for lost values or off-by-one mistakes.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.