Back to Blog
Python

Python Swap Variables Unpacking: Idiomatic One-Line Swap

python swap variables unpacking: Learn how to swap variables in Python using tuple unpacking, understand the evaluation order, and see when to prefer this idiomatic ap...

tuple unpackingvariable swapmultiple assignmentPython syntaxcode readability
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, the python swap variables unpacking pattern lets you exchange values in a single line:

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. Python constructs a tuple (b, a) from the current values, then unpacks that tuple into the targets on the left.

How the Swap Works: Evaluation Order and Tuple Creation

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, producing a tuple of values. In this case, it reads the current value of b and the current value of a, and creates the tuple (b, a).
  2. Unpack that tuple into the left-hand side targets, assigning the first element to a and the second to b.

Because the tuple is created 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 tuple creation is a lightweight operation. It does not copy the objects themselves; it only stores references. For typical variables holding integers, strings, or objects, the overhead is negligible.

Swapping More Than Two Variables

The same unpacking mechanism can swap three or more values in one statement:

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

This rotates the values: 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 rotate 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:

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:

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 a tuple (3, 1), which is then unpacked into items[0] and items[2]. This works because the indices are evaluated before the assignment, so you don't accidentally read a value that has already been overwritten.

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 using a temporary variable in a way that loses data:

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 reverse the order on the left side:

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:

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:

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 does create a tuple on the right-hand side, which involves a small allocation. 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. In CPython, the tuple is a small object, and its creation is optimized, but it is not free. 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 copies references into the tuple and 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 tuple creation 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:

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. 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 indices are 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.

python swap variables unpacking: Practical Usage and Code Ex | RYUSLOG DEV