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

Moshe Zadka moshez at math.huji.ac.il
Thu Jun 29 01:53:20 EDT 2000


On 28 Jun 2000, David White wrote:

> 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)

Short answer: never ever modify a list you're iterating on. Make a copy
first.

running-faster-is-pointless-if-you-get-the-wrong-answer-ly y'rs, Z.

--
Moshe Zadka <moshez at math.huji.ac.il>
http://www.oreilly.com/news/prescod_0300.html
http://www.linux.org.il -- we put the penguin in .com





More information about the Python-list mailing list