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
  • 55,057
  • 6
  • 42
  • 65
mr_incredible
  • 617
  • 1
  • 6
  • 18

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
  • 28,952
  • 5
  • 61
  • 78
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,152
  • 2
  • 9
  • 32
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,442
  • 2
  • 25
  • 31
Darjusch
  • 178
  • 10