Programming’s most fundamental yet crucial task is swapping two numbers, as computer algorithms, data structures, and other applications frequently require it. Python is an object-oriented, multipurpose language that offers several methods for switching two numbers. In this article, we will learn how to swap two numbers in Python.
What do you mean by Swapping numbers?
The value of one number can be swapped for the value of another number through number swapping. Let’s take an example where A = 10 and B = 20. If we were to do a number swap between these two values, A would become 20, and B would become 10. Applications involving various sorting algorithms, data transformations, etc., can benefit from the swapping process.
Note that there is no specific syntax or only one approach to swap two numbers. Multiple approaches are there in which there can be a usage of temporary variables, mathematical libraries, or in-built functions.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Approaches to Swap Two Numbers
In Python, there are many methods or approaches to swapping two numbers. Mainly, there are two approaches to swapping two numbers in Python:
Using a Temporary (extra or 3rd) variable
Without using a Temporary variable
Now, we will understand these two different approaches in Python in detail, along with their subcategories with syntaxes and examples.
Using a Temporary variable
The very first approach to swap two numbers in Python is a naive or simplest or most common approach. In this approach, to swap two numbers, we will use a third variable known as the temp variable. Let’s understand this approach using a detailed example.
Syntax:
temp = n1
n1 = n2
n2 = temp
In the above syntax, we have taken three variables n1, n2, and temp. Here, the n1 and n2 represent the two numbers, whereas the temp variable is used for exchanging or swapping two numbers.
Code Example:
# Taking two numbers input
n1 = int(input("Enter the first (n1) number to swap: "))
n2 = int(input("Enter the second (n2) number to swap: "))
temp = n1
n1 = n2
n2 = temp
print ("The value of n1 after swapping is: ", n1)
print ("The value of n2 after swapping is: ", n2)
Output:
Enter the first (n1) number to swap: 52
Enter the second (n2) number to swap: 26
The value of n1 after swapping is: 26
The value of n2 after swapping is: 52
Explanation:
In the given example, we are swapping two numbers in Python using an extra or temporary variable. Here, we are taking inputs of two numbers from the user ‘n1’ and ‘n2’. After taking input, we store the value of ‘n1’ in the ‘temp’ variable. After that, assign the value of ‘n2’ to ‘n2’ and then, finally, assign the value stored in temp to ‘n2’.
Without using a temporary variable
To swap two numbers without using a temporary variable, we have multiple approaches. In this approach, we will not be using any temp variable for storing any one out of two numbers, instead, we will use another method like Bitwise XOR, arithmetic operations, tuple packing, etc.
Let’s see what are some methods to swap two numbers without using a temporary variable. Here is the list:
Using arithmetic operations
Using Bitwise XOR method
Using comma operator
Using list method
Using tuple packing and unpacking
Now, let’s discuss each of them one by one in detail with code examples.
1. Using arithmetic operations (+, – or *, /)
To swap two numbers, we have a new approach that uses arithmetic operations and eliminates the usage of any third/extra/temp variable in Python programming. Let’s discuss this approach with its syntax and code examples.
Syntax:
Using addition and subtraction operators
n1 = n1 + n2
n2 = n1 - n2
n1 = n1 - n2
Using multiplication and division operators
n1 = n1 * n2
n2 = n1 / n2
n1 = n1 / n2
Code Example 1:
# Taking two numbers input
n1 = int(input("Enter the first (n1) number to swap: "))
n2 = int(input("Enter the second (n2) number to swap: "))
# value of two numbers before swap operations
print ("The value of n1 before swapping is: ", n1)
print ("The value of n2 before swapping is: ", n2)
# using addition and subtraction arithmetic operators for swap
n1 = n1 + n2
n2 = n1 - n2
n1 = n1 - n2
print ("The value of n1 after swapping is: ", n1)
print ("The value of n2 after swapping is: ", n2)
Output:
Enter the first (n1) number to swap: 12
Enter the second (n2) number to swap: 22
The value of n1 before swapping is: 12
The value of n2 before swapping is: 22
The value of n1 after swapping is: 22
The value of n2 after swapping is: 12
Code Example 2:
# Taking two numbers input
n1 = int(input("Enter the first (n1) number to swap: "))
n2 = int(input("Enter the second (n2) number to swap: "))
# value of two numbers before swap operations
print ("The value of n1 before swapping is: ", n1)
print ("The value of n2 before swapping is: ", n2)
# using multiplication and division arithmetic operators for swap
n1 = n1 * n2
n2 = n1 / n2
n1 = n1 / n2
print ("The value of n1 after swapping is: ", n1)
print ("The value of n2 after swapping is: ", n2)
Output:
Enter the first (n1) number to swap: 44
Enter the second (n2) number to swap: 35
The value of n1 before swapping is: 44
The value of n2 before swapping is: 35
The value of n1 after swapping is: 35.0
The value of n2 after swapping is: 44.0
Explanation:
In both these examples, we are simply applying arithmetic operators like +, -, *, and /, to swap the two n1 and n2 numbers.
2. Using Bitwise XOR method
To swap two numbers, we have a new approach that uses the bitwise XOR method and eliminates the usage of any third variable in Python programming. XOR bit manipulation works by returning 1 if the corresponding bits of either operand are different and 0 if they are the same. Let’s discuss this approach with its syntax and code examples.
Syntax:
n1 = n1 ^ n2
n2 = n1 ^ n2
n1 = n1 ^ n2
Code Example:
# Taking two numbers input
n1 = int(input("Enter the first (n1) number to swap using bitwise: "))
n2 = int(input("Enter the second (n2) number to swap using bitwise: "))
# value of two numbers before swap operations
print ("The value of n1 before swapping is: ", n1)
print ("The value of n2 before swapping is: ", n2)
# using bitwise XOR (^) operator for swap
n1 = n1 ^ n2
n2 = n1 ^ n2
n1 = n1 ^ n2
print ("The value of n1 after swapping is: ", n1)
print ("The value of n2 after swapping is: ", n2)
Output:
Enter the first (n1) number to swap using bitwise: 5
Enter the second (n2) number to swap using bitwise: 10
The value of n1 before swapping is: 5
The value of n2 before swapping is: 10
The value of n1 after swapping is: 10
The value of n2 after swapping is: 5
Explanation:
In this example, we are using the bitwise manipulation using XOR, the first operation n1 = n1 ^ n2 changes n1 to the result of n1 XOR n2. For n1 = 5 and n2 = 10, n1 becomes 15 (binary: 0101 XOR 1010 = 1111). In the combined second and third operations, n2 = n1 ^ n2 changes n2 to the new n1 XOR n2, making n2 become 5 (binary: 1111 XOR 1010 = 0101). Finally, n1 = n1 ^ n2 changes to the new n1 XOR n2, making n1 become 10 (binary: 1111 XOR 0101 = 1010).
3. Using comma operator
Another approach to swap two numbers is using a comma (,) operator that eliminates the usage of any third variable in Python programming. Let’s discuss this approach with its syntax and code examples.
Syntax:
n1, n2 = n2, n1
Code Example:
# Taking two numbers input
n1 = int(input("Enter the first (n1) number to swap using comma: "))
n2 = int(input("Enter the second (n2) number to swap using comma: "))
# value of two numbers before swap operations
print ("The value of n1 before swapping is: ", n1)
print ("The value of n2 before swapping is: ", n2)
# using comma (,) operator for swap
n1, n2 = n2, n1
print ("The value of n1 after swapping is: ", n1)
print ("The value of n2 after swapping is: ", n2)
Output:
Enter the first (n1) number to swap using comma: 92
Enter the second (n2) number to swap using comma: 87
The value of n1 before swapping is: 92
The value of n2 before swapping is: 87
The value of n1 after swapping is: 87
The value of n2 after swapping is: 92
Explanation:
In this example, we are using the comma operator to swap n1 and n2. Here, the right side creates (packs) the tuple containing n2 and n1, and then it unpacks the n1 and n2 for swapping the two numbers.
4. Using list method
Another approach to swap two numbers is using a list in Python that eliminates the usage of any third variable. This method is like arrays in Python, but here we don’t use any external library in Python. Let’s discuss this approach with its syntax and code examples.
# Taking two numbers input
n1 = int(input("Enter the first (n1) number to swap using list: "))
n2 = int(input("Enter the second (n2) number to swap using list: "))
# value of two numbers before swap operations
print ("The value of n1 before swapping is: ", n1)
print ("The value of n2 before swapping is: ", n2)
# Creating a list in Python
myList = [n1, n2]
# swapping the two list items numbers
myList[0], myLis[1] = myList[1], myList[0]
print ("The value of n1 after swapping is: ", myList[0])
print ("The value of n2 after swapping is: ", myList[1])
Output:
Enter the first (n1) number to swap using list: 4566
Enter the second (n2) number to swap using list: 233
The value of n1 before swapping is: 4566
The value of n2 before swapping is: 233
The value of n1 after swapping is: 233
The value of n2 after swapping is: 4566
Explanation:
In this example, we are creating a list of n1 and n2 variables. After creating the list, we are swapping the numbers by using the index values of n1 and n2. Here, first, the n1 is at index 0, and n2 is at index 1. Now we use the comma operator here, to swap the values of n1 and n2 by assigning the n2 index to n1, and vice versa.
5. Using functions
A very efficient approach to swap two numbers is using functions in Python that eliminate the usage of any third variable. This method is very useful and makes our code reusable, modular, etc. Here, we create a function and return the values after swapping. Let’s discuss this approach with its syntax and code examples.
Syntax:
def functionName(n1, n2):
return n2, n1
Code Example:
def swapTwoNumbers(n1, n2):
return n2, n1
# Taking two numbers input
n1 = int(input("Enter the first (n1) number to swap using function: "))
n2 = int(input("Enter the second (n2) number to swap using function: "))
# value of two numbers before swap operations
print ("The value of n1 before swapping is: ", n1)
print ("The value of n2 before swapping is: ", n2)
# swapping the two numbers using swapTwoNumbers() function
n1, n2 = swapTwoNumbers(n1, n2)
print ("The value of n1 after swapping is: ", n1)
print ("The value of n2 after swapping is: ", n2)
Output:
Enter the first (n1) number to swap using function: 3556
Enter the second (n2) number to swap using function: 454
The value of n1 before swapping is: 3556
The value of n2 before swapping is: 454
The value of n1 after swapping is: 454
The value of n2 after swapping is: 3556
Explanation:
In this example, we are creating a function swapTwoNumbers() that simply takes two input params as n1 and n2 and returns a swap of two numbers as n2, and n1.
6. Using classes and objects
Another approach to swapping two numbers is using classes and objects in Python. This method makes our code reusable, modular, and useful in cases where there are more complex behaviours. Let’s discuss this approach with its syntax and code examples.
class SwapNumbers:
def __init__(self, n1, n2):
self.n1 = n1
self.n2 = n2
def swapNumbers(self):
self.n1, self.n2 = self.n2, self.n1
# Taking two numbers input
n1 = int(input("Enter the first (n1) number to swap using class: "))
n2 = int(input("Enter the second (n2) number to swap using class: "))
# value of two numbers before swap operations
print ("The value of n1 before swapping is: ", n1)
print ("The value of n2 before swapping is: ", n2)
# swapping the two numbers using class
n = SwapNumbers(n1, n2)
n.swapNumbers()
print ("The value of n1 after swapping is: ", n.n1)
print ("The value of n2 after swapping is: ", n.n2)
Output:
Enter the first (n1) number to swap using class: 3445
Enter the second (n2) number to swap using class: 54656
The value of n1 before swapping is: 3445
The value of n2 before swapping is: 54656
The value of n1 after swapping is: 54656
The value of n2 after swapping is: 3445
Explanation:
In this example, we have defined a class called ‘SwapNumbers’ and initialised its two attributes as ‘n1’ and ‘n2’, where we are also creating a swapNumbers function to swap the two numbers. Finally, we create an instance ‘n’ of the class and call the ‘swapNumbers’ method in it.
Conclusion
In this article, we have learned the swapping of two numbers in the Python programming language. We have learned the different ways to swap two numbers along with their syntaxes, code examples, and outputs. Using a temporary variable is a straightforward and easier approach where we need not use any extra variable, while bitwise operators, classes, and functions provide efficient approaches to it. We have discussed various methods in this article, and now choosing the right method depends on you and your requirements. Understanding these approaches will enhance your problem-solving and also allow you to write efficient, modular, and readable code in Python language.
FAQs
How can I swap two numbers without a temporary variable in Python?
You can use the Bitwise operator (XOR) to swap two numbers without a temporary variable. Let p and q as two numbers. Do, p = p^q, q = p^ q, and p = p ^ q, and your swapping will be done.
Can I use the bitwise XOR approach for non-integer data types?
No, you can’t use the XOR method for non-integer types of data, as it only allows the integer data type because of its operations done in integers.
What is the most common method to swap two numbers in Python?
Using a temporary variable approach is very common to swap two numbers.
What is tuple packing and unpacking in Python, and how is it used for swapping?
In Python, several variables can have numerous values assigned to them in a single line by using tuple packing and unpacking. Since p and q are two numbers, for instance, swapping them can be done as follows: p, q = q, p.
Can swapping be done in more than 2 variables in Python?
Yes, swapping can be done in more than two numbers. A Simple way to swap more than two numbers is like, p, q, r = q, r, p using the tuple packing and unpacking method.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.