[Tutor] removing from a list
Kent Johnson
kent_johnson at skillsoft.com
Thu Aug 12 20:23:22 CEST 2004
John,
You can't do that :-)
There is an undesirable interaction between remove and iteration. It is as
if you were using this program:
>>> a = ["this",1,"that",5,"what"]
>>> i=0
>>> while i<len(a):
... if a[i]=='that' or a[i]==5:
... del a[i]
... i += 1
...
>>> a
['this', 1, 5, 'what']
Conceptually, when you delete a list item, the next item moves into its
place. But the iterator doesn't know you did this, so it increments over
the (former) next item. It's not the logical 'or' that triggers the
problem, it is having two adjacent list elements that you want to delete.
One work around is to process the list from the end, for example:
>>> a = ["this",1,"that",5,"what"]
>>> i=len(a)-1
>>> while i >= 0:
... if a[i]=='that' or a[i]==5:
... del a[i]
... i -= 1
...
>>> a
['this', 1, 'what']
Kent
At 11:03 AM 8/12/2004 -0700, 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
More information about the Tutor
mailing list