Skip to content
Advertisement

Find the indices of list items in another list only when consecutive

I earlier asked this question and the following was suggested: How to test if a list contains another list? However, the above did not answer my question.

listA=["mango","orange","guava","mango","cherry","pawpaw"]
listB=["mango","cherry","pawpaw"]

In the lists A and B above, to get the indices of listB elements in listA, I want the indices of "mango","cherry" and "pawpaw" in listA to be [3,4,5] ignoring the first "mango" since it is not part of the consecutive sequence.

Advertisement

Answer

Keep a sliding window of length equal to the length of listB

for i in range(len(listA)- len(listB) + 1):
    if listA[i:i+len(listB)] == listB:
        print([k for k in range(i,i+len(listB))])
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement