How to replace None in the List with previous value
You can use the function accumulate()
and the operator or
:
from itertools import accumulate
list(accumulate(lst, lambda x, y: y or x))
# [None, None, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5]
In this solution you take the element y
and the previous element x
and compare them using the operator or
. If y
is None
you take the previous element x
; otherweise, you take y
. If both are None
you get None
.
You can take advantage of lists being mutable
x =[None, None, 1, 2, None, None, 3, 4, None, 5, None, None]
for i,e in enumerate(x[:-1], 1):
if x[i] is None:
x[i] = x[i-1]
print(x)
output
[None, None, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5]
In Python 3.8 or higher you can do this using the assignment operator:
def none_replace(ls):
p = None
return [p:=e if e is not None else p for e in ls]