Emptying a list

Ype Kingma ykingma at accessforall.nl
Sat Sep 15 15:23:04 EDT 2001


Hello pythoneers,

The other day on the jython-users list there was a question
about emptying a list by iterating over it and removing
the elements, which failed. I gave the answer below,
and I'd like to have some more comments.

[original question deleted]

Iterating over a list that is being modified results
in undefined behaviour. A better way is:

    for i in a[:]: # iterate over a copy
         a.remove(i) # remove from original

The problem with this is that it still needs to access each element
in the list (at least twice).

When you need to remove some of the elements in a list you could
also use list comprehensions, but these always create a new list:

    a = [i for i in a if not someRemoveCondition(i)]


To empty a list in a single operation you can also:

    a[:] = [] # modify in place to become an empty list. (A)

or

    a = [] # change to refer to a new empty list object. (B)

or, preferably:

    del a[:] # modify in place deleting all entries (C)

The last variant does not create a new object, which can make a measurable
difference for garbage collection in case it avoids creating a lot of them.
This technique is also known as reusing existing objects.
I have never measured the difference between (A) and the other
two, but (C) is definitely faster than (B) in Jython.
It is probably faster in CPython, too.

[snipped the last few lines]

Ype

-- 
email at xs4all.nl



More information about the Python-list mailing list