[Tutor] removing from a list

Ertl, John John.Ertl at fnmoc.navy.mil
Thu Aug 12 20:03:00 CEST 2004


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 


More information about the Tutor mailing list