Get first element with maximum value in list of tuples in Python


We have a list of tuple. We are required to find out that tuple which was maximum value in it. But in case more than one tuple has same value we need the first tuple which has maximum value.

With itemgetter and max

With itemgetter(1) we get all the value from index position 1 and then apply a max function to get the item with max value. But in case more than one result is returned, we apply index zero to get the first tuple with maximum element in it.

Example

 Live Demo

from operator import itemgetter
# initializing list
listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
# Given list
print("Given list : \n" ,listA)
# using max() and itemgetter()
res = max(listA, key=itemgetter(1))[0]
# printing result
print("Day with maximum score is : \n",res)

Output

Running the above code gives us the following result −

Given list :
[('Mon', 3), ('Tue', 20), ('Wed', 9)]
Day with maximum score is :
Tue

With max and lambda

We use the lambda function to get the elements at index position 1 then apply the max function. Then we apply the index position 0 to get the first among multiple matches to get the final result.

Example

 Live Demo

# initializing list
listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
# Given list
print("Given list : \n" ,listA)
# using max() and lambda
res = max(listA, key = lambda i : i[1])[0]
# printing result
print("Day with maximum score is : \n",res)

Output

Running the above code gives us the following result −

Given list :
[('Mon', 3), ('Tue', 20), ('Wed', 9)]
Day with maximum score is :
Tue

With sorted

In this approach we use the sorted function with reversed equal to true condition when applying the lambda function.

Example

 Live Demo

# initializing list
listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
# Given list
print("Given list : \n" ,listA)
# using sorted() and lambda
res = sorted(listA, key = lambda i: i[1], reverse = True)[0][0]
# printing result
print("Day with maximum score is : \n",res)

Output

Running the above code gives us the following result −

Given list :
[('Mon', 3), ('Tue', 20), ('Wed', 9)]
Day with maximum score is :
Tue

Updated on: 04-Jun-2020

851 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements