list partition

David M. Cooke cookedm+news at physics.mcmaster.ca
Sun Feb 22 05:27:59 CET 2004


At some point, "Moosebumps" <Moosebumps at Moosebumps.Moosebumps> wrote:

> Is there a function that takes a list and predicate, and returns two
> lists -- one for which the predicate is true and one for which it is false?
>
> I know I can call filter(p, list) and filter( not p, list) or something like
> that, but I assume it would be more efficient to do it in one pass.

Not too hard to write your own:

def filtersplit(p, iterable):
    ptrue = []
    pfalse = []
    for x in iterable:
        if p(x):
            ptrue.append(x)
        else:
            pfalse.append(x)
    return ptrue, pfalse

> Actually I probably can't call "not p", I would have to wrap p in a function
> notP or something.  Or is there a shortcut for lambda(x) : not p(x)?  I
> guess it isn't that long : )

itertools.ifilterfalse negates the condition for you.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list