list partition

M

Moosebumps

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 know I can call filter(p, list) and filter( not p, list) or something like
that, but I assume it would be more efficient to do it in one pass.

Actually I probably can't call "not p", I would have to wrap p in a function
notP or something. Or is there a shortcut for lambda(x) : not p(x)? I
guess it isn't that long : )

MB
 
D

David M. Cooke

Moosebumps said:
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 know I can call filter(p, list) and filter( not p, list) or something like
that, but I assume it would be more efficient to do it in one pass.

Not too hard to write your own:

def filtersplit(p, iterable):
ptrue = []
pfalse = []
for x in iterable:
if p(x):
ptrue.append(x)
else:
pfalse.append(x)
return ptrue, pfalse
Actually I probably can't call "not p", I would have to wrap p in a function
notP or something. Or is there a shortcut for lambda(x) : not p(x)? I
guess it isn't that long : )

itertools.ifilterfalse negates the condition for you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,183
Messages
2,570,968
Members
47,518
Latest member
TobiasAxf

Latest Threads

Top