'List comprehension, keep highest value in a list

I want to create a list comprehension that keeps the previous value unless the next value is higher.

Example:
list_input = [3, 4, 2, 8, 9, 3, 3, 4, 20, 1]

list_output = [3, 4, 4, 8, 9, 9, 9, 9, 20, 20]

Is there a way to do this in a single list comprehension expression?



Solution 1:[1]

One way to really just do it in a list comprehension:

list_output = [m
               for m in list_input[:1]
               for x in list_input
               for m in [max(m, x)]]

Better way:

from itertools import accumulate

list_output = list(accumulate(list_input, max))

Requested explanation for the list comprehension: It does pretty much the same as this:

list_output = []
if list_input:
    m = list_input[0]
for x in list_input:
    m = max(m, x)
    list_output.append(m)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1