I often want to bucket an unordered collection in python. itertools.groubpy does the right sort of thing but almost always requires massaging to sort the items first and cat
Here's a variant of partition() from above when the predicate is boolean, avoiding the cost of a dict/defaultdict:
def boolpartition(seq, pred):
passing, failing = [], []
for item in seq:
(passing if pred(item) else failing).append(item)
return passing, failing
Example usage:
>>> even, odd = boolpartition([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
>>> even
[2, 4]
>>> odd
[1, 3, 5]