# How to Swap in Python

In this article, we will learn to swap two variables in Python.

Method 1:

a = 10 b = 5 print("Value of a is {} and value of b is {}".format(a, b)) # swaping values temp = a a = b b = temp print("After swapping, Value of a is {} and value of b is {}".format(a, b))

Output:

Value of a is 10 and value of b is 5 After swapping, Value of a is 5 and value of b is 10

Method 2:

a = 10 b = 5 print("Value of a is {} and value of b is {}".format(a, b)) # swaping values a = a ^ b b = a ^ b a = a ^ b print("After swapping, Value of a is {} and value of b is {}".format(a, b))

Output:

Value of a is 10 and value of b is 5 After swapping, Value of a is 5 and value of b is 10

Method 3:

a = 10 b = 5 print("Value of a is {} and value of b is {}".format(a, b)) # swaping values a, b = b, a print("After swapping, Value of a is {} and value of b is {}".format(a, b))

Output:

Value of a is 10 and value of b is 5 After swapping, Value of a is 5 and value of b is 10

Subscribe

Login

Please login to comment

0 Discussion