Swap two numbers in python

In this example, you will learn to swap value of two variable in python with help of different methods.

In this examples, we will define two variable with integer values and swap those two numbers using different methods like using temporary variable, using bit-wise xor operator and without using third variable method.

Python Program to Swap Two Numbers using Built-in method

For swapping variable's value, python provide a built-in method. This method works for any data type values like string, int, float and is easy to use.

Example :

    
a = 10
b = 20
print("before swapping :\n a = ",a," b = ",b)
a, b = b, a
print("after swapping :\n a = ",a," b = ",b)
    

Output :

    
before swapping : 
 a =  10  b =  20
after swapping :
 a =  20  b =  10
    

Python Program to Swap Two Numbers using Temporary Variable

Here, we will define third variable and swap value of first two variable using third one.

Example :

    
a = 10
b = 20
print("before swapping :\n a = ",a," b = ",b)
temp = a
a = b
b = temp
print("after swapping :\n a = ",a," b = ",b)
    

Output :

    
before swapping : 
 a =  10  b =  20
after swapping :
 a =  20  b =  10
    

Python Program to Swap Two Numbers using Addition and Subtraction / Multiplication and division

In this example we can use addition and subtraction operators or multiplication and division operator for swapping numbers.

Example :

    
a = 10
b = 20
print("before swapping :\n a = ",a," b = ",b)
a = a + b 
b = a - b
a = a - b
print("after swapping :\n a = ",a," b = ",b)
    

Output :

    
before swapping : 
 a =  10  b =  20
after swapping :
 a =  20  b =  10
    

Python Program to Swap Two Numbers using Bitwise xor Operator

In Python, bitwise operators are used to performing bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit.

Example :

    
a = 10
b = 20
print("before swapping :\n a = ",a," b = ",b)
a = a ^ b
b = a ^ b
a = a ^ b
print("after swapping :\n a = ",a," b = ",b)
    

Output :

    
before swapping : 
 a =  10  b =  20
after swapping :
 a =  20  b =  10
    

Share your thoughts

Ask anything about this examples