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.
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
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
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
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
Ask anything about this examples