The Python Oracle

filtered and non-filtered elements in a single pass

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind

--

Chapters
00:00 Filtered And Non-Filtered Elements In A Single Pass
00:37 Answer 1 Score 3
00:53 Answer 2 Score 2
01:10 Accepted Answer Score 5
01:34 Answer 4 Score 1
01:54 Thank you

--

Full question
https://stackoverflow.com/questions/1007...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #functionalprogramming

#avk47



ACCEPTED ANSWER

Score 5


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]



ANSWER 2

Score 3


def someFunc(trueorfalsefunc, l):
    trueList = []
    falseList = []
    for item in l:
        if trueorfalsefunc(item):
            trueList.append(item)
        else:
            falseList.append(item)
    return trueList, falseList

So, for example:

>>> someFunc(bool, [1,2,0,"", "a"])
([1, 2, 'a'], [0, ''])



ANSWER 3

Score 2


If you want to go for a one liner you can do this: (I'm switching from dicts to lists as Niklas B. suggested to improve readability)

>>> some_list=[True, False, True, False, False]
>>> reduce(lambda (true,false),x: (true + [x], false) if x else (true, false + [x]), some_list, ([],[]))
([True, True], [False, False, False])



ANSWER 4

Score 1


You could use generator comprehensions, which should help on performance and facilitate cleaner code. I really am not sure if this will be satisfactory for the rest of your program though. It depends on how you're using these returned results.

trueList = (elem for elem in list if trueOrFalseFunc(elem) )
falseList = (elem for elem in list if elem not in trueList )