Remove items from a list

Peter Otten __peter__ at web.de
Wed Sep 8 12:14:12 EDT 2004


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 example
> 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 position
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