3

I have a list with several minimum:

some_list = [1,4,6,4,1,7]

Is there a built-in function or any smart solution to get the index of the minimums?

result = [0,4]

I made it like this so far, but I prefer a shorter/easier to read the solution.

 min = 10**10
 result = [] 
 for i in range(len(some_list)):
        if some_list[i] < min:
            min = some_list[i]
            result = [i]
        elif some_list[i] == min:
            result.append(i)
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 2
    `min = 10**10` is _bad_ in two ways. First, you assume that your largest element is smaller than 10**10 (are you sure?) Second, you overwrite the built-in function `min()`. Consider writing as `myMin=max(some_list)+1`. – DYZ Mar 03 '20 at 07:32

3 Answers3

12

You can use enumerate.

some_list = [1,4,6,4,1,7]
minimum=min(some_list)
index=[idx for idx,val in enumerate(some_list) if val==minimum]
# [0,4]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
4
In [13]: import numpy as np                                                     

In [14]: values = np.array([1,4,6,4,1,7])                                       

In [15]: np.where(values==values.min())                                         
Out[15]: (array([0, 4]),)
Pygirl
  • 12,969
  • 5
  • 30
  • 43
2

Use List Comprehension to find all indexes of an item in list. Hope this is more simple.

some_list = [1,4,6,4,1,7]
result = [ i for i in range(len(some_list)) if some_list[i] == min(some_list) ]
print(result)
Arun Soorya
  • 447
  • 2
  • 9