list.pop([i]) and list.remove(x) w/ for loops
Jean-Francois Richard
jfr at genyinfo.com
Wed Jun 28 14:33:27 EDT 2000
You can't modify a list while iterating over it since the result is
unexpected.
Try to do something this way instead:
i = 0
while i < len(olist):
if olist[i].type == a:
olist.remove(olist[i])
else:
i = i + 1
"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