4 Ways to Swap 2 Variables in Python

4 Ways to Swap 2 Variables in Python

Ways to Swap 2 Variables in Python: In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. For example, if a = 5 and b = 6, then after swapping these two variables, a = 6 and b = 5. To perform this, there are many ways that one can follow.

Here in this post, I am going share 4 common ways that the Python programmers use to swap values of two variables.

1. Using a Temporary Variable

The simplest and probably most widely used method to swap two variables is to use a third temporary variable. Here the logic is simple but it requires extra memory which is often not desired.

a = 5
b = 6
temp = a
a = b
b = temp
print(a, b)

 

2. Using Addition and Subtraction Logic

This method works this way: Assign the value of the sum of the values of the two variable to the first variable. Now you have a new value of the first variable.

After getting this new variable, assign the value of the difference between the first variable and second variable to the second variable.

Now, the value of the first variable (assigned initially) is the value of the second variable.

Assign the difference of the first variable and second variable to the first variable.

Now the values are swapped.

a = 5
b = 6
a = a + b
b = a-b
a = a-b
print(a, b)

This is rarely used in practical applications, mainly because:

  • It can only swap numeric variables; it may not be possible or logical to add or subtract complex data types, like containers.
  • When swapping variables of a fixed size, arithmetic overflow becomes an issue.
  • It does not work generally for floating-point values, because floating-point arithmetic is non-associative.

3. Using XOR Operations

This method is more efficient than the earlier two methods in terms of memory. It uses XOR bitwise operations to swap the values of different variables. It is known as the XOR swap algorithm.

a = 5
b = 6
a = a^b
b = a^b
a = a^b
print(a, b)

 

4. Python’s way of Swapping – Parallel assignment

Some languages like Python and Ruby support parallel assignment. It removes the requirement of a temporary variable to swap the values of different variables.

a = 5
b = 6
a, b = b , a
print(a, b)