Python: How to swap variables without using a temporary variable

I guess everybody who has studied programming had an example of how to swap variables, all those examples because they were intended for…

Python: How to swap variables without using a temporary variable
Photo by Markus Spiske on Unsplash

I guess everybody who has studied programming had an example of how to swap variables, all those examples because they were intended for educational use did involve the usage of a temporary variable, in the following examples we will see ways to avoid the usage of a temporary variable.

Using multiple assignment

This is a “Pythonic” way and probably not every other language supports this

a = 1 
b = 2 
 
# swap 
a,b = b,a 
 
print(a) # a = 2 
print(b) # b = 1

Doing maths

Not an easy-to-read way but quite simple and clever

a = 1 
b = 2 
 
# do maths 
a = a + b # a = 3 
b = a - b # b = 1 
a = a - b # a = 2

Bitwise XOR

Let's talk a bit (pun intended) about the XOR operation, XOR compares each bit of its operands and returns 1 if bits are different, and 0 if are the same, let's explore this example

a = 1 # In binary 0001 
b = 2 # In binary 0010 
 
a = a ^ b # 0001 ^ 0010 = 0011 (3 in decimal) 
b = a ^ b # 0011 ^ 0010 = 0001 (1 in decimal) 
a = a ^ b # 0011 ^ 0001 = 0010 (2 in decimal) 
 
print(a) # a = 2 
print(b) # b = 1

How it works

1st operation, now value a contains both information of a and b.

a = a ^ b

2nd operation, since a holds the combined information XORing again with b cancels any information related to variable b.

b = a ^ b

3rd operation, now b holds the value of original a, XORing a with b again cancels the original a from variable a leaving the original b in a.

a = a ^ b

Conclusion

I hope you enjoyed this article! probably not anything that you will use in your everyday work but I think it's always nice to find and discuss about interesting tricks! :)