Pythonic : Find all consecutive sub-sequences of certain length

Pythonic : Find all consecutive sub-sequences of certain length … here is a solution to the problem.

Pythonic : Find all consecutive sub-sequences of certain length

I

have a list of integers and I want to find all consecutive subsequences of length n in this list. For example:

>>> int_list = [1,4,6,7,8,9]
>>> conseq_sequences(int_list, length=3)
[[6,7,8], [7,8,9]]

The best I can think of:

def conseq_sequences(self, li, length):
    return [li[n:n+length]
            for n in xrange(len(li)-length+1)
            if li[n:n+length] == range(li[n], li[n]+length)]

This is not overly readable. Is there any readable pythonic way to do this?

Solution

This is a more general solution for arbitrary input iterables (not just sequences):

from itertools import groupby, islice, tee
from operator import itemgetter

def consecutive_subseq(iterable, length):
    for _, consec_run in groupby(enumerate(iterable), lambda x: x[0] - x[1]):
        k_wise = tee(map(itemgetter(1), consec_run), length)
        for n, it in enumerate(k_wise):
            next(islice(it, n, n), None) # consume n items from it
        yield from zip(*k_wise)

Example:

print(*consecutive_subseq([1,4,6,7,8,9], 3))
# -> (6, 7, 8) (7, 8, 9)

The code uses Python 3 syntax and can be adapted for Python 2 if needed.

See also, What is the most pythonic way to sort dates sequences?

Related Problems and Solutions