Remove items from a list

Quinn Dunkan qdunkan1 at hotmail.com
Wed Sep 8 17:01:12 EDT 2004


Egbert Bouwman <egbert.list at hccnet.nl> wrote in message news:<mailman.3029.1094638477.5135.python-list at python.org>...
> On Wed, Sep 08, 2004 at 03:59:26AM +0000, Stan Cook wrote:
> > I was trying to take a list of files in a directory and remove all but the ".dbf" files.  I used the following to try to remove the items, but they would not remove.  Any help would be greatly appreciated.
> > 
> > x = 0
> > for each in _dbases:
> >     if each[-4:] <> ".dbf":
> >             del each            # also tried:   del _dbases[x]
> >     x = x + 1
> > 
> > I must be doing something wrong, but it acts as though it is....
> > 
> The answers you received don't tell you what you are doing wrong.
> If you replace 'del each' with 'print each' it works,
> so it seems that you can not delete elements of a list you are 
> looping over. But I would like to know more about it as well.
> egbert

"for each in ..." makes 'each' signify an element of _dbases.  Then
"del each" makes 'each' no longer signify anything.  So the above doesn't
really do anything at all.  "del _dbases[x]" however does work, but
notice that if you delete element 3, element 4 becomes element 3, etc.  Then
when 'x' is incremented to 4, you've skipped what used to be element 4 (which
is now element 3).  In general, modifying a list while iterating over it is
more trouble than it's worth.  Go with the listcomp solutions.



More information about the Python-list mailing list