[Tutor] Why is this only catching one occurance?
Bob Gailer
bgailer at alum.rpi.edu
Fri Oct 27 18:03:29 CEST 2006
Chris Hengge wrote:
> Here is my code:
> for unWantedItem in directoryList:
> try:
> if "hex" in unWantedItem.lower():
> if not "bmc" in unWantedItem.lower():
> print unWantedItem + " removed!"
> directoryList.remove(unWantedItem)
>
> This only seems to loop through once, and removes 1 of 2 occurances
> from this list that should be captured. Should "for" keep the list
> going through each instance?
"for" goes thru the list accessing item[0], item[1], item[2], etc. Let's
say "for" is on item[1] and you remove item[1]. All the subsequent items
"move left", so item[2] becomes item[1], item[3] becomes item[2], etc.
"for" then steps to item[2], skipping the original item[2].
There are several ways around this. The easiest is to process the list
backwards: for unWantedItem in directoryList[,,-1]:
--
Bob Gailer
510-978-4454
More information about the Tutor
mailing list