list partition

Peter Otten __peter__ at web.de
Sun Feb 22 03:02:14 EST 2004


Moosebumps wrote:

> Is there a function that takes a list and predicate, and returns two
> lists -- one for which the predicate is true and one for which it is
> false?

I take a slightly different approach, which is not limited to boolean
predicates:

>>> def predicate(v): return v & 1
...
>>> d = {}
>>> for i in range(10):
...     d.setdefault(predicate(i), []).append(i)
...
>>> d[True]
[1, 3, 5, 7, 9]
>>> d[False]
[0, 2, 4, 6, 8]
>>>

Peter



More information about the Python-list mailing list