Check current index and next index equal to zero python

Question:

I need to scroll through a list in Python like for example:

l = [2313, 1221, 1333, 66, 0, 0, 0, 0]

I would like if the current and the next element in the list are equal to zero replace the current and the next element by 1.

Or if current and previous element are equal to zero: replace current and previous element by 1.

How could I do this?

Answer:

You can do it like this:

l = [0, 0, 2313, 1221, 0, 1333, 66, 0, 0, 0, 0]
lCount = len(l)
next1 = False

for i in range(0, lCount-1):
    if(l[i] == 0 and l[i+1] == 0):
        l[i] = 1
        next1 = True
    elif(next1):
        l[i] = 1
        next1 = False

if(next1): # ultimo elemento caso seja 0 seguido de outro (next1 definido no ultimo loop do ciclo)
    l[-1] = 1

print(l) # [1, 1, 2313, 1221, 0, 1333, 66, 1, 1, 1, 1]
Scroll to Top