0

How does one split a list in python at all points that meet a condition? I spent time going through the many list splitting questions here, and couldn't find one that addresses this issue.

For example, given a list [1,2,4,5,2,3,5] and a condition odd number, I realize one can do something like this:

l = [1,2,4,5,2,3,5]
split = []
for item in l:
    if item%2==1:
        split.append([])
    split[-1].append(item)

and then

split == [[1, 2, 4], [5, 2], [3], [5]]

Is there a faster (assuming n appends is slow for large data sets) and/or a simple one liner or builtin function such as <module>.split(l, key=lambda item:item%2==1)?

Jeff
  • 968
  • 1
  • 10
  • 25
  • 2
    [This](http://stackoverflow.com/questions/22629252/pythonic-way-to-split-a-list-after-elements-for-which-a-given-predicate-is-true) is a similar question. IMO your approach is readable and works fine. – Sukrit Kalra Jul 18 '14 at 06:43
  • @SukritKalra True. Didn't think to search for the word predicate :). Deleting question. – Jeff Jul 18 '14 at 06:45

0 Answers0