2

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?

1
  • Comments are not for extended discussion; this conversation has been moved to chat. Commented Apr 12, 2022 at 1:03

1 Answer 1

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) 
Sign up to request clarification or add additional context in comments.

4 Comments

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?
@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 and I wouldn't be surprised if Pandas had one, too.
@mrClean Added something to hopefully clarify it.
numpy solution also did it. Thx again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.