5 Simple Ways to Swap Variables in Python
Swapping variables is a basic task in programming, and Python makes it easy with several different methods , knowing these ways can help you write better code. Let’s look at five simple methods to swap variables in Python.
1. Swap using a Temporary Variable
The easiest way to swap two variables is by using a temporary variable. This method is simple and works in most programming languages.
a = 5
b = 10
# Using a temporary variable
temp = a
a = b
b = temp
print("a =", a) # Output: a = 10
print("b =", b) # Output: b = 5
Here, we use temp to hold the value of a. Then, we set a to b, and finally, set b to temp, which still holds the original value of a. This method is easy to understand, but it does use a extra memory for the temp variable.
2. Swap Using Tuple Unpacking
Python offers tuple unpacking, which allows you to swap variables without using a temporary variable.
a = 5
b = 10
# Using tuple unpacking
a, b = b, a
print("a =", a) # Output: a = 10
print("b =", b) # Output: b = 5
In this method, Python first creates a pair (b, a) and then assigns b to a and a to b. This way of swapping doesn’t use extra memory.
3. Swap Using Arithmetic Operations
You can also swap variables by using simple math, like addition and subtraction. This method doesn’t need a temporary variable but might seem a bit complex at first.
a = 5
b = 10
# Using math
a = a + b
b = a - b
a = a - b
print("a =", a) # Output: a = 10
print("b =", b) # Output: b = 5
In this method, we first add a and b and store the result in a. Then, we find the new b by subtracting the old b from the new a. Finally, we update a by subtracting the new b. This method works well but can be harder to understand.
4. Swap Using Bitwise XOR
Swapping variables using the bitwise XOR operation is a not common but efficient technique. This method is useful when working in environments with limited resources .
a = 5
b = 10
# Using XOR
a = a ^ b
b = a ^ b
a = a ^ b
print("a =", a) # Output: a = 10
print("b =", b) # Output: b = 5
The XOR swap algorithm works because the XOR of two identical values is 0, and the XOR of any value with 0 is the value itself. However, this method is rarely used in practice due to its complexity and the availability of simpler alternatives.
5. Swap with Python Tricks
Python has many built-in functions that you can use creatively to swap variables. One such method using deque from the collections module.
from collections import deque
a = 5
b = 10
# Using deque
d = deque([a, b])
d.rotate(1)
a, b = d
print("a =", a) # Output: a = 10
print("b =", b) # Output: b = 5
While this method isn’t very common, it’s a fun way to explore Python’s features. Here, we use deque to hold a and b, and then rotate the values before assigning them back to a and b.
Conclusion
By understanding these techniques, you can make your code cleaner and more efficient. So, next time you need to swap variables, you'll have plenty of options to choose from!