list.pop([i]) and list.remove(x) w/ for loops

Stephen Hansen stephen at cerebralmaelstrom.com
Wed Jun 28 14:31:03 EDT 2000


When you are iterating over a sequence using the for loop, you can't modify
the origional loop, otherwise you'll screw things up..

[a,b,c,d] -- when you start, you are at the first index.. which points to
'a'. When you remove that item, you don't actually increase your current
index..even though your list is now [b,c,d]... so 'for' will go to the next
index... which is 2.. which points to 'c', instead of 'b'

To get around this, iterate over a copy of thes equence.

for o in olist[:]:
    if(o.type == a):
        olist.remove(o)

The [:] slice makes a copy of the sequence.

--Stephen

David White <dwhite2 at blue.seas.upenn.edu> wrote in message
news:8jdfb6$ugh$1 at netnews.upenn.edu...
> I was getting some unexpected behavior when using list.remove(x),
wondering if
> someone can tell me what's going on.
>
> I have a list of 2 kinds of objects, such as [a, a, b, b, a, b].  I wan't
to
> delete all the a objects out of the list while preserving the order of the
b
> objects.  My code looks like this:
>
> for o in olist:
>     if (o.type == a):
>        olist.remove(o)
>
> Now for some reason I get a left over a object that wasn't removed.
Anyone
> know why?  Using python 1.5.2.
>
> thanks,
> david





More information about the Python-list mailing list