Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

How to Swap Variables in Python Using Tuple Unpacking

Learn how to swap variables in Python using tuple unpacking, why the evaluation order matters, and how to avoid common mistakes.

~6 min readPython
#tuple unpacking#variable swap#multiple assignment#Python syntax
Illustration of two variables exchanging values using Python tuple unpacking, with a clean and modern design.

The One-Line Swap Using Unpacking

Swapping two variables is a common operation in any programming language. In Python, tuple unpacking lets you exchange values in a single line:

python
a = 1 b = 2 a, b = b, a

After this assignment, a holds 2 and b holds 1. No temporary variable is needed. This works because the right-hand side of the assignment is evaluated completely before any assignment happens. The current values are grouped as (b, a), then unpacked into the targets on the left.

How the Swap Works: Evaluation Order and Temporary Values

The key to understanding the unpacking swap is the order in which Python evaluates an assignment statement. When you write a, b = b, a, the interpreter does the following:

  1. Evaluate the right-hand side expressions from left to right. The current values become a temporary sequence, effectively a tuple (b, a). A simple two-name swap may be optimized by the implementation, but the evaluation order is the same.
  2. Unpack that sequence into the left-hand side targets, assigning the first element to a and the second to b.

Because the right-hand side is evaluated before any assignment, the original values are preserved. This is fundamentally different from a naive swap like a = b; b = a, which would lose the original a after the first assignment.

The temporary grouping stores references, not copies of the objects themselves. For typical variables holding integers, strings, or objects, the overhead is negligible.

Swapping More Than Two Variables

The same unpacking mechanism can exchange values across more than two variables in one statement:

python
x = 1 y = 2 z = 3 x, y, z = z, y, x

This exchanges x and z while y remains unchanged: x becomes 3, y stays 2, and z becomes 1. The right-hand side is evaluated first, producing a tuple of all three current values, then unpacked in order. This is a clean way to exchange values without multiple temporary assignments.

You can also use unpacking to assign values from a list or any iterable, as long as the number of elements matches:

python
values = [10, 20] first, second = values

For swapping, the right-hand side can be any expression that produces an iterable of the correct length, though the most common form is the simple b, a tuple.

Swapping List Elements by Index

Unpacking is not limited to standalone variables. You can swap elements inside a list using index-based assignment:

python
items = [1, 2, 3, 4] items[0], items[2] = items[2], items[0]

After this, items becomes [3, 2, 1, 4]. The right-hand side evaluates the current values at indices 2 and 0, creating the tuple (3, 1), which is then unpacked into items[0] and items[2]. Because the right-hand side is evaluated before any storage, both original values are read before either list slot changes.

This pattern is especially useful in algorithms like quicksort or when reordering elements based on a condition. It is more concise than using a temporary variable and avoids the risk of accidentally using an outdated value.

Common Mistakes: Assignment Order and Temporary Variables

A common mistake when learning Python is to write a swap as two sequential assignments, which loses data:

python
a = 1 b = 2 # Wrong: this overwrites a before b is updated a = b b = a

After this, both a and b are 2. The unpacking version avoids this by evaluating the entire right-hand side first. Another mistake is to forget to reverse the variables on the right-hand side:

python
a, b = a, b # no effect

This simply reassigns the same values. To swap, the right-hand side must be b, a.

Some developers coming from languages like C or Java might instinctively reach for a temporary variable:

python
temp = a a = b b = temp

This works, but it is more verbose and introduces an extra name. The unpacking version is shorter and clearly expresses the intent to exchange values.

Readability and Maintainability: Why Unpacking Is Idiomatic

The unpacking swap is the preferred style in Python because it is concise and self-documenting. When another developer reads a, b = b, a, they immediately understand that the values are being exchanged. The temporary-variable version requires reading three lines and mentally tracking the intermediate state.

In code reviews, the unpacking swap is widely accepted and often expected. It is part of the Pythonic idiom. Using it consistently makes your code more maintainable because it reduces the number of statements and eliminates a variable that exists only to hold a value during the exchange.

For example, in a function that needs to reorder two values based on a condition, the unpacking swap keeps the logic compact:

python
def sort_pair(x, y): if x > y: x, y = y, x return x, y

This is clearer than introducing a temporary variable inside the conditional.

Performance and Memory: What the Interpreter Actually Does

The unpacking swap may need to store the right-hand side values before assigning them. In CPython, a simple two-name swap can be optimized to stack operations, so the exact cost depends on the implementation and the expression. For most code, this overhead is negligible compared to the surrounding logic. If you are swapping variables in a tight loop that runs millions of times, you might wonder whether a temporary variable is faster. However, without profiling, you cannot assume one is significantly faster than the other.

The important point is that the unpacking swap does not copy the objects themselves. It only stores references to the original objects, then assigns those references back to the variables. For large objects, this is just a pointer assignment, not a deep copy. Memory usage is essentially the same as using a temporary variable, because both approaches hold one extra reference during the exchange.

If you are working in a performance-critical section and have measured that the temporary grouping is a bottleneck, you could fall back to a temporary variable. But in practice, the readability and clarity of the unpacking swap usually outweigh any micro-optimization. Premature optimization is rarely worth the loss of expressiveness.

Edge Cases: When Unpacking Swap Might Surprise You

Unpacking swap is straightforward, but there are a few edge cases to keep in mind.

First, the right-hand side expressions are evaluated in order. If an expression has side effects, those effects happen before any assignment. For example:

python
def get_value(label): print(f"Getting {label}") return label a = 'left' b = 'right' a, b = get_value('b'), get_value('a')

This prints Getting b and then Getting a, because the right-hand side is evaluated left to right. The values are then assigned to a and b, so a ends up as 'b' and b as 'a'. This is usually what you want, but be aware that the evaluation order is deterministic.

Second, the unpacking swap requires that both sides have the same number of elements. If you try a, b, c = b, a, Python raises a ValueError because the tuple has two elements but the left side expects three. This is a useful safety check, but it means you cannot swap a variable number of items without additional logic.

Third, if the variables are not in the same scope, you cannot swap them with a single assignment. For example, you cannot swap two global variables from inside a function without declaring them global or using a mutable container. The unpacking swap works only on assignable targets in the current scope.

Finally, when swapping list elements, be careful with negative indices. The expression items[-1], items[0] = items[0], items[-1] works as expected because the right-hand side is evaluated before assignment. However, if you are swapping elements that depend on each other's positions, the right-hand side evaluation ensures you read the original values, so there is no risk of accidentally using an already-updated element.

Understanding these edge cases helps you use the unpacking swap confidently in a variety of contexts, from simple variable exchange to in-place list reordering.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.