[Tutor] trouble with list.remove() loop

Steven D'Aprano steve at pearwood.info
Tue Sep 28 13:22:36 CEST 2010

On Tue, 28 Sep 2010 06:55:15 pm Christian Witts wrote:

> You are mutating the list that you are iterating over so in essence
> you are looking at the word in list index 0, testing it, and removing
> it, then moving onto list index 1 but now your list has 'amazing' in
> index 0 so that does not get checked.
> The simplest way is to iterate through a new list with this
>      for word in candidates[:]:
> That will create a new list that you will iterate over while you
> mutate the original list.

Another technique is to iterate over the list backwards, so you are only 
ever deleting words you've already seen:

for i in range(len(candidates)-1, -1, -1)):
    word = candidates[i]
    if some_test():
        del candidates[i]

I know the series of -1, -1, -1 is ugly, but that's what it takes.

Steven D'Aprano

More information about the Tutor mailing list