A tuple is an immutable list of values. Iteration and indexes work the same way as lists, but they cannot be modified. While list literals use square brackets, tuple literals use parenthesis.
x = (1,4,6) print(x[0]) 1 for val in x: print(val)
Assignment
(x,y) = (4,'Fred') print(y) Fred print(x) 4
Iteration
Method items() in dictionary returns a list of tuples. In a for loop we use as many iteration variables as there are elements in the tuples
for k,v in dictionary.items(): print(k, v) for (k,v) in dictionary.items(): print(k, v)
Comparison Operators
The first element of a tuple is the most significant. The comparison operator is applied to one element at a time starting with the first element in both tuples
(0,1,2) < (4,6,2) True
Sorting a list of tuples
# Prints pairs ordered by keys for k,v in sorted(dictionary.items()): print(k,v) # Sort by values c = {'a':10 , 'b':1 , 'c':22} tmp = list() for k,v in c.items(): tmp.append((v,k)) print(tmp) [(10,'a'), (1,'b'), (22,'c')] tmp = sorted(tmp, reverse=True) print(tmp) [(22,'c'), (10,'a'), (1,'b')]