Tuples in Python-1

A Tuple in Python is an immutable collection of elements.
The following code creates a tuple.

t1=(1,2,3)
print(t1)
Output
(1, 2, 3)
Tuples can also contain elements of many types.
t1=(1,”Two”,3)
print(t1)
Output
(1, ‘Two’, 3)

List of Tuples
l1=[(2,”Abhay”,”Mumbai”),(1,”Vivek”,”Kolkata”)]
print(l1)
Sorting a list of Tuples.
l1=[(2,”Abhay”,”Mumbai”),(1,”Vivek”,”Kolkata”)]
print(l1)
l1.sort()
print(l1)
Output
[(2, ‘Abhay’, ‘Mumbai’), (1, ‘Vivek’, ‘Kolkata’)]
[(1, ‘Vivek’, ‘Kolkata’), (2, ‘Abhay’, ‘Mumbai’)]
As the output shows; Sorting is done on the basis of the first element of the tuple.

The sorted method works the same way.
l1=[(2,”Abhay”,”Mumbai”),(1,”Vivek”,”Kolkata”)]
print(l1)
l1.sort()
print(l1)
l1=sorted(l1,reverse=True)
print(l1)

Output
[(2, ‘Abhay’, ‘Mumbai’), (1, ‘Vivek’, ‘Kolkata’)]
[(1, ‘Vivek’, ‘Kolkata’), (2, ‘Abhay’, ‘Mumbai’)]
[(2, ‘Abhay’, ‘Mumbai’), (1, ‘Vivek’, ‘Kolkata’)]

Sorting using different elements. This introduces the lambda expressions. We will learn more about this later.

l1=[(2,”Abhay”,”Mumbai”),(1,”Vivek”,”Kolkata”)]
print(l1)
#sort by zeroth element
l1.sort(key=lambda x:x[0])
print(l1)
#sort by first element
l1.sort(key=lambda x:x[1])
print(l1)
#sort by second element
l1.sort(key=lambda x:x[2])
print(l1)

Output
[(2, ‘Abhay’, ‘Mumbai’), (1, ‘Vivek’, ‘Kolkata’)]
[(1, ‘Vivek’, ‘Kolkata’), (2, ‘Abhay’, ‘Mumbai’)]
[(2, ‘Abhay’, ‘Mumbai’), (1, ‘Vivek’, ‘Kolkata’)]
[(1, ‘Vivek’, ‘Kolkata’), (2, ‘Abhay’, ‘Mumbai’)]

 

 

Leave a Reply