Remove items from a list

Dan Bishop danb_83 at yahoo.com
Thu Sep 9 01:26:46 EDT 2004


qdunkan1 at hotmail.com (Quinn Dunkan) wrote in message news:<a0a1779c.0409081206.21b2757e at posting.google.com>...
> 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.

And if for some reason you can't use listcomps, you can use an approach like:

for (x, each) in enumerate(_dbases):
   if each[-4:] != ".dbf":
      # don't use del, just mark the slot as empty
      _dbases[x] = None
# Now filter out Nones
_dbases = [x for x in _dbases if x is not None]



More information about the Python-list mailing list