-4

I have a list which has two values (name, number) as shown below:

lst = [['ABC', 1.4976557902646848], ['LMN', 1.946130694688788], ['QRS', 3.0039607941124085]]

I want to get the name value of the maximum number in this list. In this example it will be 'QRS'

Tak
  • 3,536
  • 11
  • 51
  • 93

1 Answers1

1

Use the max built-in function with key kwarg. Refer to the docs of max for more details.

It will return the sublist that has the max number, from which we take the first element (the "name").

li = [['ABC', 1.4976557902646848], ['LMN', 1.946130694688788], ['QRS', 3.0039607941124085]]

print(max(li, key=lambda x: x[1])[0])
# QRS

You can use itemgetter instead of defining the lambda:

from operator import itemgetter

li = [['ABC', 1.4976557902646848], ['LMN', 1.946130694688788], ['QRS', 3.0039607941124085]]

print(max(li, key=itemgetter(1))[0])
# QRS
DeepSpace
  • 78,697
  • 11
  • 109
  • 154