-1

I would like to iterate a list and remove every integer in the list that includes a zero. However, enumerate doesn't include a number in my list if it's the same as the previous one. Why does this occur and how can I prevent that?

a = [0, 1, 1, 0, 0, 1, 1, 0, 0]
index = []

for d, e in enumerate(a):
    print(d, e)
    if e == 0:
        a.pop(d)
        index.append(d)
        
print(a)
print(index)

What the output is:

0 0
1 1
2 0
3 1
4 1
5 0
[1, 1, 0, 1, 1, 0]
[0, 2, 5]

What I would like the output to be:

0 0
1 1
2 1
3 0
4 0
5 1
6 1
7 0
8 0
[1, 1, 1, 1]
[1, 2, 5, 6]

1 Answers1

0

You can try:

a = [0, 1, 1, 0, 0, 1, 1, 0, 0]
index = []
b = []

for d, e in enumerate(a):
    print(d, e)
    if e == 1:
        b.append(e)
        index.append(d)

print(b)
print(index)

Output:

0 0
1 1
2 1
3 0
4 0
5 1
6 1
7 0
8 0
[1, 1, 1, 1]
[1, 2, 5, 6]
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61