[Tutor] removing from a list

Ertl, John John.Ertl at fnmoc.navy.mil
Thu Aug 12 20:30:34 CEST 2004

I will give that a try...l have not played with comprehension or filtering

John Ertl 
-----Original Message-----
From: Lloyd Kvam [mailto:lkvam at venix.com]
Sent: Thursday, August 12, 2004 11:09
To: Ertl, John
Cc: Tutor Python
Subject: Re: [Tutor] removing from a list

removing elements from the list that you are iterating through does not
work well.

The common work-around is to iterate through a copy of the list:
for each in a[:]:       # use slice notation to create a copy of list

Another good alternative is to build a new list, possibly binding it to
the same name as the original list.  A list comprehension works well for

a = [each for each in a if each not in ("that",5)]

If you make the filtering expression a function, you can also use the
filter builtin:

a = filter(func, a)

I now generally prefer creating a new list using a list comprehension.

On Thu, 2004-08-12 at 14:03, Ertl, John wrote:
> All,
> I am having a problem with remove().
> Remove seems to make the for each loop skip over the element that follows
> the removed element.
> I have been able to reproduce my problem on a very simple scale.
> >>>a = ["this",1,"that",5,"what"]
> >>>for each in a:
>       print each
>       if each == "that" or each == 5:
>          a.remove(each)
> this
> 1
> that
> what
> You can see...the 5 was never checked in the loop but if I print out a...5
> is still part of the list.
> >>> a
> ['this', 1, 5, 'what']
> The element "that" was successfully removed but 5 was never checked and
> therefore never removed...Is this how remove should work?
> I also noticed that if I do not have a logical and/or in the checking or I
> do not actually remove the element there is no problem.
> Thanks
> John Ertl
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:  603-653-8139
fax:    801-459-9582

More information about the Tutor mailing list