Remove items from a list

Dan Perl dperl at
Wed Sep 8 19:29:16 CEST 2004

Sorry, I missed that.  And yes, that should be the problem.  It's *A*
problem, for sure.  Always a bad idea to modify the structure of a list
(deleting or inserting items) while iterating through it, but it's so easy
to forget that.  Creating another list from the first one by filtering or
with a list comprehension should be the preferred solution, unless the
intention is to have this list used in more than one place and have the
changes reflected in all those places.


"Peter Otten" <__peter__ at> wrote in message
news:chnb4k$3qn$05$1 at
> Dan Perl wrote:
> > But Stan says he tried something like that (see the comment in his code)
> > and
> > it was still not working.  I would still need a more complete code
> > to reproduce the problem and figure out what went wrong.
> The following example might make it clearer:
> >>> files = "a.dbf b.dbf x.txt".split()
> >>> for index, fn in enumerate(files):
> ...     print "checking", fn
> ...     if fn.endswith(".dbf"):
> ...             print "deleting", files[index]
> ...             del files[index]
> ...
> checking a.dbf
> deleting a.dbf
> checking x.txt
> >>>
> The iterator operating on the files list keeps track of its current
> in the list by a simple index and is unaware of any changes to that list.
> If you delete an item _before_ or equal to that index position it will
> still be incremented on the next pass of the for loop, and therefore you
> never see item[n] that has become item[n-1] effectively by deleting one of
> its predecessors.
> To avoid this kind of trouble, Mel iterates over the list in reverse
order -
> deleting items _after_ the current position cannot confuse the iteration.
> Peter

More information about the Python-list mailing list