Collect subsequences of consecutive integers I've written a function to split a list into several lists with consecutive integers, e.g.:

extract_subsequences([1,2,3,7,8,9])



  [[1, 2, 3], [7, 8, 9]]


extract_subsequences([1,2,3])



  [[1, 2, 3]]


extract_subsequences([1,2,3, 10])



  [[1, 2, 3], [10]]


extract_subsequences([1,2, 4,5, 8,9])



  [[1, 2], [4, 5], [8, 9]]


This is the code that I came up with:

import numpy as np

def extract_subsequences(seq):
    def split_sequence(seq):
            for i in np.arange(1, len(seq)):
                if seq[i] != seq[i - 1] + 1:
                    break

            if i &lt; len(seq) - 1:
                return seq[:i], seq[i:]
            else:
                if seq[-1] == seq[-2] + 1:
                    return seq, []
                else:
                    return seq[:-1], [seq[-1]]

    res = []
    last = seq
    while len(last) &gt; 1:
        first, last = split_sequence(last)
        res.append(first)

    if len(last) == 1:
        res.append(last)

    return res


Can someone help me improve this code? It's kind of difficult to read with all the indices and special cases, and for the same reasons it was also quite difficult to write. I would very much appreciate a better way of thinking about this problem.
@Peter Taylor has a good idea, but there is more to be improved

You should add some tests

Python is often described as Batteries included
This is a perfect example to use itertools.groupby()



from itertools import groupby
import doctest

def extract_seq(seq):
    &quot;&quot;&quot;
    Splits sequence into consecutive lists
    
    args:
        seq (list): A sorted sequence

    &gt;&gt;&gt; extract_seq([1,2, 4,5, 8,9])
    [[1, 2], [4, 5], [8, 9]]

    &gt;&gt;&gt; extract_seq([1,2,3])
    [[1, 2, 3]]

    &gt;&gt;&gt; extract_seq([1,2,3,7,8,9])
    [[1, 2, 3], [7, 8, 9]]

    &gt;&gt;&gt; extract_seq([1,2,3,10])
    [[1, 2, 3], [10]]
    &quot;&quot;&quot;
    return [
        [x for _, x in g]
        for k, g in groupby(
            enumerate(seq), 
            lambda i_x : i_x[0] - i_x[1]
        )
    ]

if __name__ == &quot;__main__&quot;:
    doctest.testmod()