James Jameson
James Jameson

Reputation: 57

How can I extract a sublist with the lowest integer value from a nested list?

If I have a nested list as follows:

foods = [['Category', 'Carbs', 'Calories'], ['SWEET POTATO', '23.4', '100'], ['TOMATOES', '5.1', '23'], ['BEETS', '16.28', '65'], ['LETTUCE', '2.23', '13']]

I want to find and print the sublist with the lowest Calorie count. I have tried the following:

    lowcal = foods[0]
for x in foods:
    if x[2] < lowcal[2]:
        lowcal = x
    else:
        continue
print (lowcal)

But I am getting the wrong output, I am getting: `['SWEET POTATO', '23.4', '100']

When I should be getting: ['LETTUCE', '2.23', '13']

Upvotes: 0

Views: 44

Answers (2)

Sam
Sam

Reputation: 1415

Your problem is that your values for Carbs and Calories are strings (you have them in quotes!), rather than integers. Also, you start with lowcal = foods[0] which is your headers, not a food with calories and carbs. I'd suggest the following:

foods = [
    ['Category', 'Carbs', 'Calories'],
    ['SWEET POTATO', '23.4', 100],
    ['TOMATOES', '5.1', 23],
    ['BEETS', '16.28', 65],
    ['LETTUCE', '2.23', 13]
]
lowcal = foods[1]
for x in foods[2:]:
    if int(x[2]) < int(lowcal[2]):
        lowcal = x
>>> print (lowcal)
['LETTUCE', '2.23', 13]

Victory! Hope that helps, happy coding!

Upvotes: 1

Austin
Austin

Reputation: 26039

You can use min() on your list with key as third element:

min([x for x in foods[1:]], key=lambda x: int(x[2]))

Upvotes: 1

Related Questions