Machine Markus
Machine Markus

Reputation: 89

How to determine several minimum in a list?

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)

Upvotes: 3

Views: 1232

Answers (3)

Ch3steR
Ch3steR

Reputation: 20669

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]

Upvotes: 12

Arun Soorya
Arun Soorya

Reputation: 484

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)

Upvotes: 2

Pygirl
Pygirl

Reputation: 13339

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]),)

Upvotes: 4

Related Questions