Python Program to swap two numbers without using third variable
Given two variables n1 and n2. The task is to swap the values of both the variables without using third variable.
Examples:
X : 10
Y : 20
After swapping X and Y, we get :
X : 20
Y : 10
A : 'Hello'
B : 'World'
After swapping A and B, we get :
A : 'World'
B : 'Hello'
Method 1 :- Using simple built-in method
left , right = right , left
This method works for any data type values like string, int, float and is easy to use.
Python
x = 5
y = 7
print ( "Before swapping: " )
print ( "Value of x : " , x, " and y : " , y)
x, y = y, x
print ( "After swapping: " )
print ( "Value of x : " , x, " and y : " , y)
|
Output:
Before swapping:
Value of x : 5 and y : 7
After swapping:
Value of x : 7 and y : 5
Method 2 :- Using Bitwise XOR operator
x ^= y
y ^= x
x ^= y
This method only works for integers and works faster because this method uses bit operation (for same values, output = 0 and for different values, output = 1) .
Python
x = 5
y = 10
print ( "Before swapping: " )
print ( "Value of x : " , x, " and y : " , y)
x ^ = y
y ^ = x
x ^ = y
print ( "After swapping: " )
print ( "Value of x : " , x, " and y : " , y)
|
Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5
Method 3 :- Using Addition and Subtraction Operators
x = x + y
y = x - y
x = x - y
This method works for variables that have numeric values.
Python
x = 5.4
y = 10.3
print ( "Before swapping: " )
print ( "Value of x : " , x, " and y : " , y)
x = x + y
y = x - y
x = x - y
print ( "After swapping: " )
print ( "Value of x : " , x, " and y : " , y)
|
Output:
Before swapping:
Value of x : 5.4 and y : 10.3
After swapping:
Value of x : 10.3 and y : 5.4
Method 4 :- Using Division and Multiplication Operators
x = x * y
y = x / y
x = x / y
This method works for variables that have numeric values other than 0 .
Python
x = 5.4
y = 10.3
print ( "Before swapping: " )
print ( "Value of x : " , x, " and y : " , y)
x = x * y
y = x / y
x = x / y
print ( "After swapping: " )
print ( "Value of x : " , x, " and y : " , y)
|
Output:
Before swapping:
Value of x : 5.4 and y : 10.3
After swapping:
Value of x : 10.3 and y : 5.4
Method 4: Using both bitwise operators and arithmetic operators:
Python3
x = 5 ;
y = 10 ;
print ( "Before swapping: " ) ;
print ( "Value of x : " , x, " and y : " , y) ;
x = (x & y) + (x|y) ;
y = x + (~y) + 1 ;
x = x + (~y) + 1 ;
print ( "After swapping: " )
print ( "Value of x : " , x, " and y : " , y)
|
Output:
Before swapping:
Value of x : 5 and y : 10
After swapping:
Value of x : 10 and y : 5
Last Updated :
16 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...