Tuple is somehow similar to a List in Python except that the elements in a tuple is immutable (cannot be change or modified throughout the whole program). Tuple is a read-only List.
#this is an empty tuple. t0 = () #this is a tuple. t1 = (1, 2, 3) #this is also a tuple. t2 = 1, 2, 3 #these are single element tuples. #single element tuples must have #trailing comma. t3 = (1, ) t4 = 1,
Using tuple packing and unpacking method to swap 2 variables without using a 3rd variable.
a = 1 b = 2 print(a) print(b) #swap variables using tuple packing and unpacking a,b = b,a print('After swapping...') print(a) print(b)
The right hand side of the equation is assigning the tuple (b,a) to (2,1). This is call packing. The left hand side is assigning variable ‘a’ to 2 and variable ‘b’ to 1. Putting the elements of a tuple to variables is call unpacking. Number of variables on LHS must be equal to number of elements in the tuple on the RHS