Backfill a list with preceding list items

Say I have a list containing the values 1, 0 and -1. I am trying to find a method of creating a new list so that the preceding values determine the current values. So that for every zero that appears, if a positive number was the last seen in the list, it should become 1. Similarly, with negative numbers.

#Example:

x = [1, 1, 1, 0, 0, -1, -1, 1, 0, 1, 0, 0, 0, -1, -1, 0, 0, 1, 1, 1, 1]

so x would become

x = [1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1,-1,-1, 1, 1, 1, 1]

Anyone know of a decent way of doing this? Thanks.

>Solution :

Using a simple loop:

x = [1, 1, 1, 0, 0, -1, -1, 1, 0, 1, 0, 0, 0, -1, -1, 0, 0, 1, 1, 1, 1]

out = []
prev = 1 # default value
for i in x:
    if i == 0:
        out.append(prev)
    else:
        out.append(i)
        prev = i

output:

[1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1]

Leave a Reply