Alex Rivera | Logout

Removing Item From List - during iteration - what's wrong with this idiom?

Asked 2010-05-24T11:54:40.147
30

As an experiment, I did this:

letters=['a','b','c','d','e','f','g','h','i','j','k','l']
for i in letters:
    letters.remove(i)
print letters

The last print shows that not all items were removed ? (every other was).

IDLE 2.6.2      
>>> ================================ RESTART ================================
>>> 
['b', 'd', 'f', 'h', 'j', 'l']
>>> 

What's the explanation for this ? How it could this be re-written to remove every item ?

Edit
Report

1 Answer

8

You cannot modify the list you are iterating, otherwise you get this weird type of result. To do this, you must iterate over a copy of the list:

for i in letters[:]:
  letters.remove(i)
answered 2010-05-24T12:00:59.253

Your Answer