Python - getting all minimal elements and their indices from a list

I have a list with a minimal element that is present several times, for example

a = [1,2,1,1,4,5,6]

And I want python to return element 1 and all indices in the list where there is 1. I tried using

min_index, min_value = min(enumerate(a), key=operator.itemgetter(1))

which gives only the index, where 1 occurs first.

Any help is appreciated.

+5
source share
2 answers

determine the minimum element, and then check it for other elements in the list.

def locate_min(a):
    smallest = min(a)
    return smallest, [index for index, element in enumerate(a) 
                      if smallest == element]

which will return the tuple (min_element, [location, location, ...]). If I understand you correctly, this is what I think you want. For instance:

>>> locate_min([1, 2, 1, 1, 4, 5, 6])
(1, [0, 2, 3])

. , for-loop. ( , , )

def locate_min(a):
    min_indicies = []
    smallest = min(a)
    for index, element in enumerate(a):
            if smallest == element: # check if this element is the minimum_value
                    min_indicies.append(index) # add the index to the list if it is

    return smallest, min_indicies
+10

:

minimum = min(a)
indices = [i for i, v in enumerate(a) if v == minimum]
+9

All Articles