Search code examples
pythonlistincrementindices

return all indices of first elements in a list where subsequent values increase incrementally


Need to find indices very similar to here

But I have a list of multiple groups of incrementing values, e.g. lst = [0,1,2,7,8,9]

Expected output: [0,3]


Solution

  • Version with a simple loop:

    lst = [0,1,2,7,8,9]
    
    prev = float('-inf')
    out = []
    for i,v in enumerate(lst):
        if v!=prev+1:
            out.append(i)
        prev = v
    out
    

    Same thing with a list comprehension and zip:

    out = [i for i, (a,b) in enumerate(zip([float('-inf')]+lst, lst)) if a+1!=b]
    

    Variant with itertools.pairwise (python ≥3.10):

    from itertools import pairwise
    out = [0]+[i for i, (a,b) in enumerate(pairwise(lst), start=1) if a+1!=b]
    

    output: [0, 3]