0

I'm facing rather bizarre situation with lists. It appears that Python is very selective about what zeros it will remove in this case:

count = 0
a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]

for x in a:
    if x == 0:
        a.remove(x)
        count += 1

print(a, count)

Only 6 out of 10 zeros are removed. Why ?

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
mr_incredible
  • 837
  • 2
  • 8
  • 21

3 Answers3

3

A far better solution is to just create a new list that does not contain the 0s:

b = [x for x in a if x != 0]
count = len(a) - len(b)
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
0

To workaround the issue described by the guys in comments you can do the following:

count = 0
a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]
for x in a.copy():
    if x == 0:
        a.remove(x)
        count += 1
print(a, count)

Then you will be iterating through the original a, while simultaneously reducing it by 0 whenever you encounter it.

Caveat:

>>> False == 0
True
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
0
x = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]

list(filter(lambda a: a != 0, x))

output

['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9]
shahaf
  • 4,750
  • 2
  • 29
  • 32
Darjusch
  • 188
  • 13