How can I get a set of (possibly overlapping) slices in a Python list based on items matching a criterion?


Suppose I have a python list l=[1,2,3,4,5]. I would like to find all x-element lists starting with elements that satisfy a function f(e), or the sublist going to the end of l if there aren't enough items. For instance, suppose f(e) is e%2==0, and x=3 I'd like to get [[2,3,4],[4,5]].

Is there an elegant or "pythonic" way to do this?

Using a list comprehension:

>>> l = range(1,6)
>>> x = 3
>>> def f(e):
        return e%2 == 0
>>> [l[i:i+x] for i, j in enumerate(l) if f(j)]
[[2, 3, 4], [4, 5]]