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.
I'd just do it like this:
minimum = min(a)
indices = [i for i, v in enumerate(a) if v == minimum]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With