How to Build a Running Maximum List in Python

Compute a list where each element is the maximum of all numbers seen so far from an input list.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 16 views 0 copies

Python code

14 lines
Python 3.9+
def running_maximum(numbers):
    result = []
    current_max = float('-inf')
    for num in numbers:
        if num > current_max:
            current_max = num
        result.append(current_max)
    return result

if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6]
    max_list = running_maximum(numbers)
    print(f"Input:  {numbers}")
    print(f"Output: {max_list}")

Output

stdout
Input:  [3, 1, 4, 1, 5, 9, 2, 6]
Output: [3, 3, 4, 4, 5, 9, 9, 9]

How it works

The function running_maximum iterates over each number once. It maintains a current_max variable that holds the largest value encountered so far. For each number, if it's greater than the current max, the max is updated; otherwise, it stays the same. The updated max is then appended to the result list. This algorithm runs in O(n) time and uses O(1) extra space besides the output list.

Common mistakes

  • Forgetting to initialize `current_max` properly; using 0 can break for negative numbers.
  • Updating `current_max` only when a new max is found but appending the wrong value.
  • Trying to use `max()` on the entire prefix each time, leading to O(n²) complexity.

Variations

  1. Use `itertools.accumulate(numbers, max)` to achieve the same result in one line.
  2. Use a list comprehension with a temporary variable if you prefer a functional style.

Real-world use cases

  • Tracking the highest score seen so far while processing a stream of game events.
  • Calculating cumulative record highs in financial time series data for analytics dashboards.
  • Monitoring peak resource usage (like CPU or memory) over a series of measurements.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.