1

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?

mrLimpio
  • 45
  • 4
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/243806/discussion-on-question-by-mrclean-list-comprehension-keep-highest-value-in-a-li). – Samuel Liew Apr 12 '22 at 01:03

1 Answers1

5

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)
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
  • Can't use itertools I only have access to numpy, pandas and few other modules in the application. The list comprehension solution works great, thx for sharing! However I don't fully grasp what is going on. Do you mind walking me through what happens? – mrLimpio Apr 11 '22 at 20:25
  • 2
    @mrClean You have access to third-party modules but not access to a standard library module that comes with Python? Why? That's really odd. Are you sure? Also: quick googling found a [NumPy solution](https://stackoverflow.com/a/7251598/12671057) and I wouldn't be surprised if Pandas had one, too. – Kelly Bundy Apr 11 '22 at 20:29
  • @mrClean Added something to hopefully clarify it. – Kelly Bundy Apr 11 '22 at 20:33
  • numpy solution also did it. Thx again. – mrLimpio Apr 11 '22 at 21:07