[Tutor] Why is this only catching one occurance?

Kent Johnson kent37 at tds.net
Fri Oct 27 12:02:33 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?

The problem is that when you remove the item from the list, the iterator 
that is looping over the list gets confused and skips the next item. 
(The iterator keeps an internal counter that is not updated when you 
remove an item.) See http://effbot.org/zone/python-list.htm#modifying 
for more.

The simplest fix is to use a list comprehension to create a new list 
with only the elements you want, and assign it to the same name:

directoryList = [ item for item in directoryList if 'hex not in 
item.lower() or 'bmc' in item.lower() ]

Note I changed the sense of the conditional because it is now selecting 
items to include.

The list comp doesn't have exactly the same result as your (intended) 
code, it creates a new list rather than modifying the old one in place. 
Most of the time this doesn't matter but if you have other references to 
dictionaryList only one will be changed.

Kent



More information about the Tutor mailing list