filtered and non-filtered elements in a single pass

functional-programming, python

Solution

Try this, using iterators:

from itertools import tee

def partition(lst, pred):
    l1, l2 = tee((pred(e), e) for e in lst)
    return (x for cond, x in l1 if cond), (x for cond, x in l2 if not cond)

Use it like this, and remember that the values returned are iterators:

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
evens, odds = partition(lst, lambda x: x%2 == 0)

If you need lists for some reason, then do this:

list(evens)
> [0, 2, 4, 6, 8]
list(odds)
> [1, 3, 5, 7, 9]

Problem

Filter function returns a sublist of elements which return true for a given function. Is it possible to get the list of elements which return false in a different list without going over the entire list again. Example: `trueList,falseList = someFunc(trueOrFalseFunc,list)` PS : I know it can be done by initializing two empty lists and appending elements to each based on the return value of the function. The list under consideration can be potentially very huge and there might very few elements that might return true. As the append function is costly, is there a better way to do it ?

Original source