Replace nulls in list with previous item

I have a list that has some null value interspersed in it. I would like to replace nulls with the previous value actual value. Note that there can be multiple nulls in a row.

thanks much
image

@Jpeele_JDB See if this helps:

toNestList = lambda x: x if any(isinstance(i, list) for i in x) else [x]
OUT = [[x if x else i[j-1] for j,x in enumerate(i)] for i in toNestList(IN[0])]

This would not work as intended if you have 2 nulls back to back or if index 0 is a null.

1 Like

@Jpeele_JDB And this should take care of the back to back nulls:

toNestList = lambda x: x if any(isinstance(i, list) for i in x) else [x]
OUT = []
for i in toNestList(IN[0]):
	out = []
	for x in i:
		if x:
			out.append(x)
		else:
			out.append(out[-1])
	OUT.append(out)

This would not work as intended if index 0 is a null.

2 Likes

Pythonless option. I use this in my ReplaceNulls node in Crumple.

2 Likes

@GavinCrump That’s the 1st thing I tried but missed the @L2 in haste and assumed “if” didn’t work as usual! Thanks for pointing it out.

1 Like

If very rarely works (as desired), no worries - I quite like the Python approach as well!

1 Like

I think Python approach is better compare to Node,
because if 2 consecutive null is coming in a list than “List.ShiftIndices” Will not give appropriate,

1 Like

Ah yes sorry i misunderstood the intent or your script (I overlooked the shift). The Python approach is best here, you’re right.