How to del item of a list in loop?

skull skullw at sina.com.cn
Sat Jan 15 19:48:31 EST 2005


skull <skullw at sina.com.cn> writes:

Thank you for your replys.
lst[:] is did a solution, it makes a copy of list specially for iteration and 
removes items from the original one.

but I still have an other thing to worry about coming with this way: does 
performance sucks when the list is big enough?
It makes a copy operation!

here is a faster and 'ugly' solution:

lst = [1, 2, 3]
i = 0
while i < len(lst):
    if lst[i] == 2:
        lst.remove(i)
    else:
        i += 1

> 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.
>
> - skull



More information about the Python-list mailing list