There are several ways to swap two numbers in python coding(variable value), from traditional methods used in other languages to Pythonic one-liners.
In this post, you'll learn:- What it means to swap two numbers
- Different methods to perform the swap
- The Pythonic way (and why it’s awesome)
Swapping Of Two Numbers in Python Programming
Getting Started
Swapping two numbers means exchanging their values. For example: a = 5
b = 10
After swapping:
a = 10
b = 5
Swapping of two numbers in python is one of the most basic programming exercises and a great way to understand variable manipulation. Now, let’s see how this can be achieved in Python.
Swap Two Numbers in Python Using a Temporary Variable
Using a temporary variable, swapping of two numbers in Python is a simple and clear method. Here's how you can do it:
Example: # Input values
a = 5
b = 10
print("Before swapping:")
print("a =", a)
print("b =", b)
# Swapping using a temporary variable
temp = a
a = b
b = temp
print("\nAfter swapping:")
print("a =", a)
print("b =", b)
Output:
Before swapping:
a = 5
b = 10
After swapping:
a = 10
b = 5
Swapping two numbers using a temporary variable is easy to understand and works in all programming languages, but it requires extra memory for the temporary variable. The method below swaps two numbers without using a third variable by performing arithmetic operations, thereby avoiding the use of extra memory.
Swap Without Third Variable
Swapping two variables without using a third (temporary) variable in Python can be done in several ways. Here are the most common ones:
Using Arithmetic Operations
Example: a = 5
b = 10
# Swapping
a = a + b # a = 15
b = a - b # b = 5
a = a - b # a = 10
print("a =", a)
print("b =", b)
Problem: Be cautious with large integers, as they can cause overflow in some programming languages (though this is not usually an issue in Python due to its support for arbitrary-precision integers). To avoid overflow, a clear alternative method is using Bitwise XOR.
Using Bitwise XOR
a = 5
b = 10
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b) # Output: 10 5
Problem: This method only works for integers and is a bit more obscure, so it’s less commonly used in practice. To overcome this Python provides a clean and elegant way to swap values using tuple unpacking
Pythonic Way (Tuple Unpacking)
a = 5
b = 10
# Swapping
a, b = b, a
print("a =", a)
print("b =", b)
Summary
Swapping of two numbers is a foundational concept in Python programming. Python, being a high-level language, provides a concise and elegant way to do this through tuple unpacking. While older methods using temporary variables or arithmetic still work, the Pythonic way is recommended for clarity and simplicity.
Thanks