0

The task is to remove all the zeros from a list, so I wrote the following code:

a = [9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]
for i in a:
    if i == 0:
        a.remove(i) 
print(a)

the output is: [9, 9, 1, 2, 1, 1, 3, 1, 9, 0, 0, 0, 9]

for some reason it removes only one zero after the penultimate 9 and then stops. Could anyone explain why didn't it remove every single one?

mqueue
  • 1
  • 1

1 Answers1

3

Your problem is that you are altering a list while you iterate over it. Do this:

a = [9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]
a = [a for a in a if a != 0]
print(a)

Prints [9, 9, 1, 2, 1, 1, 3, 1, 9, 9]

Tiki
  • 760
  • 1
  • 8
  • 16
  • 1
    For a little more background on why you should not modify a list you are iterating over: https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/ – Mason3k Mar 19 '21 at 21:57