Sam
Sam

Reputation: 15

How do I find the max value in a nested list using a function?

The list given is

[["A",3.1],["B",8.90]]

I need to print the max value from the list in this statement:

B has the highest value of 8.90

I tried using this code but it does not work and only returns me ["8"]

def maxnumber():
    list=[]
    for letter in values:
        list.append(max(letter[1]))
    return list
print(maxnumber())

Upvotes: 0

Views: 80

Answers (1)

Trelta Sebastion
Trelta Sebastion

Reputation: 66

You can acheive this with this code:

def get_max(input_list):
    max_list = max(input_list, key=lambda x: x[1])
    return max_list

list_to_check = [["A",3.1],["B",8.90]]
result = get_max(list_to_check)
print(f"{result[0]} has the highest value of {result[1]}")

This will print out: "B has the highest value of 8.9"

Upvotes: 2

Related Questions