How to del item of a list in loop?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sat Jan 15 04:57:42 EST 2005


Reinhold Birkenfeld wrote:
> skull wrote:
>> Hi everybody, it is my first post in this newsgroup.
>> I am a newbie for python though I have several years development experience in c++.
>> recently, I was stumped when I tried to del item of a list when iteration.
>> 
>> here is the wrong way I did:
>> 
>> lst = [1, 2, 3]
>> for i in lst:
>>     print i
>>     if i == 2: 
>>        lst.remove(i)
>> 
>> the result is:
>> 
>> 1
>> 2
>>>>>
>> 
>> as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'.
>> apparently, 'marked-and-sweep' is a solution to deal with this issue.
>> but I think there SHOULD BE more 'wise' trick. I want to get your help.
> 
> Quick solution:
> 
> for i in lst[:]
> 
> iterates over a copy.

Addition: In Py2.4, I can't find a problem with

for i in reversed(lst)

Any objections?

Reinhold



More information about the Python-list mailing list