In this article, we will learn about how to write python program to swap two numbers without using third variable.
Getting Started
The task is to swap two numbers in python without using any other variable.
For example,
Let’s assume a and b are two numbers where, a = 50 and b = 60.
Now, we need to write a python program to swap these two numbers without using third variable. So, output should be a = 60 and b = 50
There are multiple ways to achieve above tasks.
- Using Tuple Packing and Unpacking
- Using XOR bitwise operation
- Using Multiplication and Division Operation
- Using Bitwise Operation
1. Using Tuple Packing and Unpacking
Tuple packing an unpacking is the easiest and simplest way to swap two numbers in python without third variable.
It can be done as shown below –
print ( "Before swap: num1 =" , num1, "num2 =" , num2) |
print ( "After swap: num1 =" , num1, "num2 =" , num2) |
Here,
- Statement num1, num2 = num2, num1 does the actual swapping process. Rest of the lines in above code example are just to show the output.
Output:
Before swap: num1 = 50 num2 = 60 |
After swap: num1 = 60 num2 = 50 |
2. Using XOR bitwise operation
XOR operation can also be used to swap two variables in python without using third variable. It can be done as shown below –
a = int ( input ( "Enter the value of a: " )) |
b = int ( input ( "Enter the value of b: " )) |
Here,
- We have used XOR operator, i.e. ^, for our swap operation.
Output:
3. Using Multiplication and Division Operation
There is an alternate option to above program too. We can also use multiplication and division operation to swap two variables in python without using third variable.
It can be shown as below –
print ( "Before swapping:" ) |
print ( "Value of a:" , a, "and b:" , b) |
print ( "Value of a:" , a, "and b:" , b) |
Here,
- We have used multiplication and division only to swap two numbers in python.
Output:
4. Using Bitwise Operation
Bitwise operation can also be used to write python program to swap two numbers without using third variable as shown below –
print ( "Before swapping:" ) |
print ( "Value of a:" , a, "and b:" , b) |
print ( "Value of a:" , a, "and b:" , b) |
Here,
- We are using two’s complement feature and swapping the variables.
Output:
We have also covered many other ways to swap two numbers in python. You can have a look at them if you want. Learn more about python at official site.