Replace None in list with leftmost non none value

IIUC, you could use itertools.accumulate to generate a forward fill:

>>> from itertools import accumulate
>>> a = [None,1,2,3,None,4,None,None]
>>> list(accumulate(a, lambda x,y: y if y is not None else x))
[None, 1, 2, 3, 3, 4, 4, 4]

a = [None,1,2,3,None,4,None,None]

start = next(ele for ele in a if ele is not None)
for ind, ele in enumerate(a):
    if ele is None:
        a[ind] = start
    else:
        start = ele
print(a)
[1, 1, 2, 3, 3, 4, 4, 4]

You also only need to set start to a value if the first element is None:

if a[0] is None:
   start = next(ele for ele in a if ele is not None)
for ind, ele in enumerate(a):
    if ele is None:
        a[ind] = start
    else:
        start = ele
print(a)

Tags:

Python