Remove items from a list

Mel Wilson mwilson at the-wire.com
Wed Sep 8 08:08:29 EDT 2004


In article <mailman.3029.1094638477.5135.python-list at python.org>,
Egbert Bouwman <egbert.list at hccnet.nl> wrote:
>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.

   One use of `del` is to remove a name from a namespace,
and that's what it's doing here:  removing the name 'each'.

   A paraphrase of what's going on is:

        for i in xrange (len (_dbases)):
            each = _dbases[i]
            if each[-4:] <> ".dbf":
                del each

and we happily throw away the name 'each' without touching
the item in the list.

   The way to remove items from a list is (untested code):

        for i in xrange (len (a_list)-1, -1, -1):
            if i_want_to_remove (a_list[i]):
                del a_list[i]

Going through the list backwards means that deleting an item
doesn't change the index numbers of items we've yet to
process.  `del a_list[i]` removes from the list the
reference to the object that was the i'th item in the list
(under the hood, a Python list is implemented as an array of
references.)

   This is one reason list comprehensions became popular so
fast.

        Regards.        Mel.



More information about the Python-list mailing list