How to find all positions of the maximum value in a list?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Finding every position of the maximum value is a small problem that still exposes a common mistake: list.index only returns the first match. A correct solution needs to handle duplicates, define behavior for empty input, and stay readable enough that the intent is obvious.
The Clear Two-Step Solution
For an ordinary Python list, the clearest approach is to compute the maximum once and then collect all indices where the value matches that maximum.
Output:
This solution is readable and fast enough for most real code.
Why list.index Is Not Enough
A lot of people reach for this:
That only returns the first matching index. It answers "where is one maximum" instead of "where are all maxima." For unique maxima, that may be fine. For duplicated maxima, it is incomplete.
Handle Empty Input Deliberately
max([]) raises ValueError, so a real helper should define what happens for an empty list. A common policy is to return an empty list.
That is not the only valid policy. Some codebases prefer to raise on empty input because "no maximum exists" is itself an error. The important part is to choose deliberately.
One-Pass Version for Streams
If the input is very large or cannot be traversed twice, use a one-pass approach.
This avoids calling max and then iterating again, which is useful for generators or large streams.
Return the Maximum Value Too When Helpful
Often the caller needs both the maximum value and all of its positions. Returning both can make downstream code simpler.
That avoids recalculating the maximum in the caller.
NumPy and Pandas Versions
If the data already lives in NumPy or pandas, use tools from that ecosystem instead of converting back to plain lists.
This keeps the code aligned with the structure that already holds the data.
Common Pitfalls
A common mistake is using list.index and assuming it finds every matching position. It only finds the first one.
Another issue is forgetting to define behavior for empty input. That turns a tiny helper into a hidden runtime exception.
Developers also sometimes recompute the maximum inside a loop, which is needlessly expensive and less readable than calculating it once.
Summary
- Use
maxplusenumeratefor the clearest all-positions solution. - '
list.indexis not enough when the maximum value appears more than once.' - Decide explicitly how empty input should behave.
- Use a one-pass solution when the input should not be traversed twice.
- Stick with NumPy or pandas helpers when the data already lives there.

