Getting all the min elements and its indices from a list

determine the minimum element, and then check it against 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 a tuple (min_element, [location, location, ...]). If I understand you correctly, this is what I think you want. For your example:

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

This example uses a list comprehension. If you're not familiar with this, it's roughly equivalent to the following for-loop version. (use the first version, this is just to help your understanding of how it works)

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

I'd just do it like this:

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

Tags:

Python

List