The predicate-based partition is called partition . It would be more idiomatic for me to implement partition as a separate function, rather than repeating its insides specifically for odd and even numbers. Python 3 Recipes Itertools has the following implementation:
def partition(pred, iterable): 'Use a predicate to partition entries into false entries and true entries' # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 t1, t2 = tee(iterable) return filterfalse(pred, t1), filter(pred, t2)
It uses filterfalse (as described in @Lack) and tee defined in this module. So your top-level code will look like this:
odds, evens = partition(is_even, range(10))
source share