When it is required to find the maximum element in a tuple list (i.e list of tuples), the 'max' method and the 'operator.itemgetter' method can be used.
The itemgetter fetches a specific item from its operand.
The 'max' method gives the maximum value present in an iterable that is passed as argument to it.
Below is a demonstration of the same −
Example
from operator import itemgetter
my_list = [('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)]
print ("The list is : ")
print(my_list)
my_result = max(my_list, key = itemgetter(1))[0]
print ("The name that has the maximum value is : ")
print(my_result)Output
The list is :
[('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)]
The name that has the maximum value is :
MinExplanation
- The required libraries are imported.
- The list of tuples is defined, and is displayed on the console.
- The 'max' method is used to go through the list, and specify the key as the first element of every tuple inside the list.
- This result is assigned to a value.
- It is displayed as output on the console.