[Tutor] removing from a list
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
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
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
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:
> 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:
> 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.
> John Ertl
> Tutor maillist - Tutor at python.org
1 Court Street, Suite 378
Lebanon, NH 03766-1358
More information about the Tutor