-2

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]

Hud
  • 301
  • 1
  • 12

1 Answers1

2

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]

mozway
  • 194,879
  • 13
  • 39
  • 75