"Canonical" way of deleting elements from lists

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Jan 9 07:29:06 EST 2008


Robert Latest:
> Fredrik Lundh wrote:
> >     keywords = filter(None, keywords) # get "true" items only
>
> Makes seinse. BTW, where can I find all methods of the built-in types?
> Section 3.6 only talks about strings and mentions the list append() method
> only in an example. Am I too stupid to read the manual, or is this an
> omission?

filter isn't a method of list, it's a free function.

For most situations that solution with filter(None,keywords) is good
enough (but it filters away all false items, so it filters away None,
0, empty things, etc, too).
The following one is an in-place version (it may be faster with
Psyco), but you usually don't need it:


def inplacefilter(pred, alist):
    """inplacefilter(pred, alist): filters the given list like
filter(),
    but works inplace, minimizing the used memory. It returns None.

    >>> pr = lambda x: x > 2
    >>> l = []
    >>> inplacefilter(pr, l)
    >>> l
    []
    >>> l = [1,2,2]
    >>> inplacefilter(pr, l)
    >>> l
    []
    >>> l = [3]
    >>> inplacefilter(pr, l)
    >>> l
    [3]
    >>> l = [1,2,3,1,5,1,6,0]
    >>> r = filter(pr, l) # normal filter
    >>> r
    [3, 5, 6]
    >>> inplacefilter(pr, l)
    >>> r == l
    True
    """
    slow = 0
    for fast, item in enumerate(alist):
        if pred(item):
            if slow != fast:
                alist[slow] = alist[fast]
            slow += 1
    del alist[slow:]


You may want to avoid the enumerate() too if you use Psyco and you
need max speed.

Bye,
bearophile



More information about the Python-list mailing list