Hi, I want to iterate over a list, printing each item and subsequently deleting it, so that at the end, the list is empty, while all the numbers are printed out. I have tried two tactics (to me the logic for both is the same, just checked to spot the problem), but in either case, neither is the list fully empty after the iteration, nor are all the numbers printed. Can somebody tell me what is the problem, and how can I implement what I am trying to do?

Attachments untitled.jpg 59.39 KB
5 Years
Discussion Span
Last Post by Cupidvogel

You must not insert or remove items in a list while iterating on this list. In your case, you could simply use

for x in a:
    print x
a[:] = ()

If you want to delete only some items, use a pattern like

a = range(10)
print a

def keep_me(item):
   print item
   return item % 2

a[:] = (x for x in a if keep_me(x))
print a
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.