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 append
s 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)
?