Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading