## 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)
```

`itertools.groupby`

looks for contiguous substrings in the input , for example,`6, 7, 8, 9`

. It is based on the example from the docs that shows how to find runs of consecutive numbers :The key to the solution is differencing with a range generated by

enumerate() so that consecutive integers all appear in same group

(run).`itertools.tee`

+`zip`

allows pressing k Direction iteration substring – >pairwise recipe`from the Summary of itertools`

docs.`Next(islice(iterator, n, n), None)`

from the`consume`

recipe there .

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?