Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all the min elements and its indices from a list

Tags:

python

list

I have a list that has a minimum element that is present multiple times like

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

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

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

which gives only the index where 1 occurs first.

like image 645
user62089 Avatar asked Feb 26 '13 20:02

user62089


2 Answers

I'd just do it like this:

minimum = min(a)
indices = [i for i, v in enumerate(a) if v == minimum]
like image 150
Blender Avatar answered Oct 03 '22 11:10

Blender


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
like image 22
Ryan Haining Avatar answered Oct 03 '22 13:10

Ryan Haining