4

I have a very strange bug and I can't see where I go wrong. I want to loop over a list of objects

objects =  [<object 1>, <object 2>, <object 3>, <object 4>, <Query_Category 5>, <object 6>] 

and I do a simple

for i, object in enumerate(objects):
    print "delete ", object
    objects.pop(i)

and the output is

delete  <Query_Category 1>
delete  <Query_Category 3>
delete  <Query_Category 4>
delete  <Query_Category 5>
delete  <Query_Category 6>

so the loop ignored the second element? This result is reproducible, meaning if I run it again it leads to the same outcome??? This is probably not reproducible for you, since I guess this is caused by something strange in my code??? But I have no idea what to look for? Is there sum fundamental python principle I am missing here? thanks carl

carl
  • 4,216
  • 9
  • 55
  • 103
  • 4
    Modifying the object that you're iterating over is almost never a good idea. What are you trying to accomplish with this? – nathan.medz Apr 01 '16 at 17:41

1 Answers1

5

Do not modify container you are iterating over inside the loop. Due to pop operation your container changes and thus - iteration over it fails (skips an element).

If you just want to iterate over collection and destroy it at the end - pop from it till it is not empty

a = range(10)

while len(a):
  print a.pop(0)

gives

0
1
2
3
4
5
6
7
8
9

as expected.

Thus in your case

while len(objects):
    object = objects.pop(0)
    print "delete ", object
lejlot
  • 64,777
  • 8
  • 131
  • 164