Python Program to Swap Two Numbers

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

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.

a, b = b, a

Method 2:

In this method we can use addition and subtraction operators.

a = a + b
b = a - b
a = a - b

Method 3:

We can also swap numbers using multiplication and division operator in following way.

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.

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.

Leave a Comment

Your email address will not be published. Required fields are marked *