posted Oct 21

# how to find the largest value in a list and its index with python

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

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

which returns 9 here. To find the index, there is the function, 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]``````

1,760 points
6 1