How to find all positions of the maximum value in a list?
I have a list:
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
max element is 55 (two elements on position 9 and 12)
I need to find on which position(s) the maximum value is situated. Please, help.
a.index(max(a))
will tell you the index of the first instance of the largest valued element of list a
.
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
The chosen answer (and most others) require at least two passes through the list.
Here's a one pass solution which might be a better choice for longer lists.
Edited: To address the two deficiencies pointed out by @John Machin. For (2) I attempted to optimize the tests based on guesstimated probability of occurrence of each condition and inferences allowed from predecessors. It was a little tricky figuring out the proper initialization values for max_val
and max_indices
which worked for all possible cases, especially if the max happened to be the first value in the list — but I believe it now does.
def maxelements(seq):
''' Return list of position(s) of largest element '''
max_indices = []
if seq:
max_val = seq[0]
for i,val in ((i,val) for i,val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices