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?

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.