How to del item of a list in loop?

Bengt Richter bokr at oz.net
Sun Jan 16 01:38:01 EST 2005


On Sat, 15 Jan 2005 15:27:08 -0500, skull <skullw at sina.com.cn> 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.
>
>Thanks in advance.
>
No one seems to have suggested this in-place way yet,
so I'll trot it out once again ;-)

 >>> lst = [1, 2, 3]
 >>> i = 0
 >>> for item in lst:
 ...    if item !=2:
 ...        lst[i] = item
 ...        i += 1
 ...
 >>> del lst[i:]
 >>> lst
 [1, 3]


Regards,
Bengt Richter



More information about the Python-list mailing list