'Getting index of min from 2D list in python

I have a 2d list and I am trying to get the minimum from each row in the list, then get the x-value of the minimum but I am having trouble figuring out how to do this. For example, if my list is:

[[12, 11, 440], [9191, 20, 10], [220, 1030, 40]] 

I want to find the minimum of each sublist and the x-value of the index for the minimum. So in the first sublist my min would be 11 and the index of it would be 1. Also, I want to avoid using numpy for this.



Solution 1:[1]

A simple list comprehension will do:

[lst.index(min(lst)) for lst in l]

assuming l is your original list. This results in

[1, 2, 2]

If there is more than one minimum in a sub-list (for example, all numbers are the same), this will return the index of the first one.

Solution 2:[2]

The usual approach works: enumerate, and min(sequence, key=...):

data = [[12, 11, 440], [9191, 20, 10], [220, 1030, 40]] 

for idx,inner in enumerate(data):
    idx_v, v = min(enumerate(inner), key=lambda value:value[1])
    print(f"Inner list # {idx} is {inner}. Its min value {v} is index {idx_v}")

for

Inner list # 0 is [12, 11, 440]. Its min value 11 is index 1
Inner list # 1 is [9191, 20, 10]. Its min value 10 is index 2
Inner list # 2 is [220, 1030, 40]. Its min value 40 is index 2

only the first of the minimal values will be given - if you need all use:

data = [[12, 11, 440], [9191, 20, 10], [220, 1030, 40], [40, 40, 40]] 

for idx,inner in enumerate(data):
    min_val = min(inner)

    all_mins = [v for v in enumerate(inner) if v[1]==min_val]
    for i,v in all_mins:
        print(f"Inner list # {idx} is {inner}. min value {v} at index {i}")

to get

Inner list # 0 is [12, 11, 440]. min value 11 at index 1
Inner list # 1 is [9191, 20, 10]. min value 10 at index 2
Inner list # 2 is [220, 1030, 40]. min value 40 at index 2
Inner list # 3 is [40, 40, 40]. min value 40 at index 0
Inner list # 3 is [40, 40, 40]. min value 40 at index 1
Inner list # 3 is [40, 40, 40]. min value 40 at index 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2