Better yet, use itertools.groupby:
def h(lst, cond): remain = lst for last in (l for l in lst if cond(l)): group = itertools.groupby(remain, key=lambda x: x < last) for start in group.next()[1]: yield start, last remain = list(group.next()[1])
Usage: lst = range (10) cond = lambda x: x% 2 print list (h (lst, cond))
will print
[(0, 1), (1, 3), (2, 3), (3, 5), (4, 5), (5, 7), (6, 7), (7, 9), (8, 9)]
odwl
source share