Partition list with predicate

Jared Grubb jared.grubb at gmail.com
Wed Apr 23 12:59:25 EDT 2008


I want a function that removes values from a list if a predicate evaluates
to True. The best I could come up with is:

def extract(lst, pred):
    idx = 0
    ret = []
    for obj in lst[:]:
        if pred(obj):
            ret.append(obj)
            lst.pop(idx)
        else:
            idx += 1
    return ret

Anybody have a better, more Pythonic solution? One of my failed attempts was
this code, which fails when the predicate itself has "state":

def extract(lst, pred):
    # BAD: Would not work in a case like pred = "extract every other object"
    ret = filter(lst, pred)
    for obj in ret:
        lst.remove(obj)
    return ret
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080423/ed9bc3e7/attachment.html>


More information about the Python-list mailing list