How to del item of a list in loop?

Fredrik Lundh fredrik at pythonware.com
Sat Jan 15 04:31:37 EST 2005


"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)'.

the internal loop counter is incremented whether you remove stuff or not, so
when you're moving things around by removing items in the middle, the loop
will skip over items.  this is basic for-in usage, and any decent tutorial should
explain this.


to fix this, you can build a new output list, loop backwards, or loop over a
copy.  the last is easiest to implement:

    lst = [1, 2, 3]
    for i in lst[:]:
        print i
        if i == 2:
            lst.remove(i)

but the others may have advantages in certain use cases.


if you want more details, see the language reference:

    http://docs.python.org/ref/for.html

(note the warning)

</F> 






More information about the Python-list mailing list