I want to replace the None in the list with the previous variables (for all the consecutive None). I did it with if and for (multiple lines). Is there any way to do this in a single line? i.e., List comprehension, Lambda and or map
And my idea was using the list comprehension but I was not able to assign variables in a list comprehension to set a previous value.
I have got a similar scenario in my project to handle None in such a way, the thing is I don't want to write 10 lines of code for the small functionality.
def none_replace(ls):
ret = []
prev_val = None
for i in ls:
if i:
prev_val = i
ret.append(i)
else:
ret.append(prev_val)
return ret
print('Replaced None List:', none_replace([None, None, 1, 2, None, None, 3, 4, None, 5, None, None]))
Output:
Replaced None List: [None, None, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5]