How to find all positions of the maximum value in a list?
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