To find the smallest value in a list with python, a solution is to use the function min():
>>> l = [4,7,1,4,1,6,9]
>>> min(l)
1
which returns 1 here. To find the index, there is the function index(), example:
>>> l.index(min(l))
2
Note: this function only returns the first index found. To find all the indexes of the smallest value (if there is several occurrences of the smallest value), we can do like in this example:
>>> indexes = [i for i, x in enumerate(l) if x == min(l)]
>>> indexes
[2, 4]
To find if there is several times the min value in the list, a solution is to use the python function count(), example:
>>> l = [4,7,1,4,1,6,9]
>>> min_value = min(l)
>>> min_value
1
>>> l.count(min_value)
2
it is then possible to write a simple function that returns the index(es):
>>> def get_indexes_min_value(l):
... min_value = min(l)
... if l.count(min_value) > 1:
... return [i for i, x in enumerate(l) if x == min(l)]
... else:
... return l.index(min(l))
...
>>>
>>> get_indexes_min_value(l)
[2, 4]
References
Liens | Site |
---|---|
Python List min() Method | tutorialspoint.com |
How to find all occurrences of an element in a list? | stackoverflow |
Find the smallest number in a python list and print the position | stackoverflow |
Python List index() Method | tutorialspoint |
Finding the index of an item given a list containing it in Python | stackoverflow |
Getting the index of the returned max or min item using max()/min() on a list | stackoverflow |
Python: finding lowest integer | stackoverflow |
Find the minimum value in a python list | stackoverflow |
How to return all the minimum indices in numpy | stackoverflow |
numpy.argmin | scipy doc |