1

Possible Duplicate:
python equivalent of filter() getting two output lists (i.e. partition of a list)

Is there any built-in function or maybe some module in python standard library, that simulates Enumerable.partition behaviour from Ruby and iterates over an object just once to get two lists/tuples based on a predicate function passed?

Community
  • 1
  • 1
Kirill Zaitsev
  • 4,511
  • 3
  • 21
  • 29
  • it's here: http://docs.python.org/dev/library/itertools.html#itertools-recipes. And this has been asked a number of times. http://stackoverflow.com/questions/4578590/python-equivalent-of-filter-getting-two-output-lists-i-e-partition-of-a-list – tokland Sep 12 '12 at 12:00

1 Answers1

1

Stolen shamelessly from this question - you can use the tee function from itertools:

from itertools import tee

def split_on_condition(seq, condition):
    l1,l2 = tee((condition(item),item) for item in seq)
    return (i for p, i in l1 if p), (i for p, i in l2 if not p)
Community
  • 1
  • 1
codebox
  • 19,927
  • 9
  • 63
  • 81