Here you will get python program to swap two numbers with and without using temporary variable.
Python Program to Swap Two Numbers Using Temporary Variable
1 2 3 4 5 6 7 8 9 10 |
a = 10 b = 20 print("before swapping\na=", a, " b=", b) temp = a a = b b = temp print("\nafter swapping\na=", a, " b=", b) |
Output
before swapping
a= 10 b= 20
after swapping
a= 20 b= 10
Python Program to Swap Two Numbers Without Using Temporary Variable
Method 1:
Python provides a way to directly swap two number without temporary variable. It can be done in following way.
1 |
a, b = b, a |
Method 2:
In this method we can use addition and subtraction operators.
1 2 3 |
a = a + b b = a - b a = a - b |
Method 3:
We can also swap numbers using multiplication and division operator in following way.
1 2 3 |
a = a * b b = a / b a = a / b |
This method will not work when one of the number is 0.
Method 4:
It is another method in which we use bitwise xor operator.
1 2 3 |
a = a ^ b b = a ^ b a = a ^ b |
Comment below if you have queries or know any other way to swap numbers in python.