How to find the smallest value in a list and its index with python ?

Published: March 28, 2019

DMCA.com Protection Status

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