Swap two tuples in Python


The program is written in Python and it swaps the values of two variables a and b. Initially, a is assigned a value of 10 and b is assigned a value of 20. The program then prints the values of a and b before swapping. Next, the program swaps the values of a and b using tuple unpacking. A temporary variable t is created to store the value of a, which is then used to assign the value of b to a and the value of t to b. Finally, the program prints the values of a and b after swapping.

Source Code

a=10
b=20
print("Before Swap A :",a)
print("Before Swap b :",b)
#First Method
#a , b = b, a
t = a
a = b
b = a
print("After Swap A :",a)
print("After Swap b :",b)

Output

Before Swap A : 10
Before Swap b : 20
After Swap A : 20
After Swap b : 20

Example Programs