Sequence splitting

schickb schickb at gmail.com
Thu Jul 2 22:56:50 EDT 2009


I have fairly often found the need to split a sequence into two groups
based on a function result. Much like the existing filter function,
but returning a tuple of true, false sequences. In Python, something
like:

def split(seq, func=None):
    if func is None:
        func = bool
    t, f = [], []
    for item in seq:
        if func(item):
            t.append(item)
        else:
            f.append(item)
    return (t, f)

The discussion linked to below has various approaches for doing this
now, but most traverse the sequence twice and many don't apply a
function to spit the sequence.
http://stackoverflow.com/questions/949098/python-split-a-list-based-on-a-condition

Is there any interest in a C implementation of this? Seems too trivial
to write a PEP, so I'm just trying to measure interest before diving
in. This wouldn't really belong in intertool. Would it be best
implemented as a top level built-in?

-Brad



More information about the Python-list mailing list