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

Published: March 27, 2019

DMCA.com Protection Status

To find the largest number in a list with python, a solution is to use the function max():

>>> l = [4,7,9,4,1,6,9]
>>> max(l)
9

which returns 9 here. To find the index, there is the function index(), example:

>>> l.index(max(l))
2

Note: this function only returns the first index found. To find all the indexes of a maximum value (if there is several occurrences of the maximum value), we can do like in this example:

>>> indices = [i for i, x in enumerate(l) if x == max(l)]
>>> indices
[2, 6]

To find if there is several times the max value in the list, a solution is to use the python function count(), example:

>>> l = [4,7,9,4,1,6,9]
>>> max_value = max(l)
>>> max_value 
9
>>> l.count(max_value)
2

it is then possible to write a simple function that returns the index(es):

>>> def get_indexes_max_value(l):
...     max_value = max(l)
...     if l.count(max_value) > 1:
...             return [i for i, x in enumerate(l) if x == max(l)]
...     else:
...             return l.index(max(l))
... 
>>> get_indexes_max_value(l)
[2, 6]

References