5 Best Ways to Swap Two Variables in One Line in Python

πŸ’‘ Problem Formulation: Swapping two variables involves exchanging their values. In Python, one may encounter various scenarios necessitating this switchβ€”a common task. For instance, given two variables a=10 and b=20, we want to swap their values such that a=20 and b=10.

Method 1: Tuple Unpacking

The tuple unpacking method utilizes Python’s built-in feature to assign multiple variables in a single statement. The variables on the left-hand side of the assignment are repopulated with the values from the tuple on the right-hand side simultaneously. This is a Pythonic and memory-efficient way to swap values without the need for a temporary variable.

Here’s an example:

a, b = 10, 20
a, b = b, a

Output:

a = 20
b = 10

By placing both variables on the left and a tuple on the right, Python automatically unpacks the tuple values into the variables, effectively swapping them. This process is intuitive, requiring no intermediate steps or additional memory for a temporary variable.

Method 2: Arithmetic Operations

The arithmetic operations method performs a swap by utilizing addition and subtraction to exchange the variables’ values. This approach should be used with caution as it can lead to data loss with very large integers or float types due to overflow or precision limitations.

Here’s an example:

a, b = 10, 20
a = a + b
b = a - b
a = a - b

Output:

a = 20
b = 10

This method temporarily makes one variable (a) hold the sum of both initial values. Then, variable (b) gets reassigned to the new (a) minus the original (b), which is equal to the original (a). The final line assigns (a) to the original (b) by subtracting the new (b) from the sum. While clever, the drawbacks such as possible overflow or precision loss make this method less desirable.

Method 3: Using XOR Bitwise Operation

This swap method leverages the XOR bitwise operator. It’s a fascinating and efficient technique that doesn’t require additional memory and avoids potential overflow issues. However, it is limited to integer values and can be less readable than other methods.

Here’s an example:

a, b = 10, 20
a = a ^ b
b = a ^ b
a = a ^ b

Output:

a = 20
b = 10

The XOR operation is used three times to perform the swap. When the same value is XOR’ed with itself, it results in zero. Applying XOR with a zeroed middle variable effectively swaps the values between variables. This method is fascinating from a computer science perspective but may be confusing in practical programming.

Method 4: Using a Single Line with a Comma

Python also allows swapping two variables by reassigning them in a single line using the comma operator. This is essentially shorthand notation for the tuple unpacking method described in Method 1. It’s a succinct and readable approach that Python programmers frequently favor.

Here’s an example:

a, b = 10, 20
a, b = b, a

Output:

a = 20
b = 10

This one-liner is elegant and straightforward, illustrating Python’s ability to perform complex operations with minimal syntax. It’s generally the preferred method for swapping variables, as it clearly communicates the intention with no extraneous details.

Bonus One-Liner Method 5: Swapping with ‘*’ Operator

A less-known but interesting swap idiom takes advantage of Python’s extended iterable unpacking. By using the ‘*’ operator, you can swap multiple values simultaneously. This method is most useful for variables in a list context and when you need to swap more than two items.

Here’s an example:

a, b = 10, 20
*a, b = b, *a

Output:

a = [20]
b = 10

This example demonstrates swapping the values by packing and then unpacking them using the asterisk operator. Note that variable a becomes a list after the swap, so this method might require further adjustments if the variables must remain as individual integers.

Summary/Discussion

  • Method 1: Tuple Unpacking. Simple and pythonic. It works with any data types. Its simplicity may also hide its functionality at a quick glance.
  • Method 2: Arithmetic Operations. Clever use of arithmetic. Beware of overflow or precision loss with non-integer types. Not as intuitive as other methods.
  • Method 3: XOR Bitwise Operation. Interesting from a computer science standpoint. Only works with integers. Less readable and conceptual for most programmers.
  • Method 4: Single Line with a Comma. Clean and clear. Pythonic and favored for its brevity. Demonstrates a prime feature of Python’s syntactic elegance.
  • Bonus Method 5: Swapping with ‘*’ Operator. Useful for unpacking iterables. Swaps into lists, which may necessitate post-processing. A quirky and lesser-known feature of Python.