user1376377 user1376377 - 1 year ago 47
Python Question

Find indexes of sequence in list in python

I am quite new and I hope it's not too obvious, but I just can't seem to find a short and precise answer to the following problem.

I have two lists:

a = [2,3,5,2,5,6,7,2]
b = [2,5,6]

I would like to find when all the indexes of the second list (
) are in the first list (
), so that I get something like this:

indexes of b in a:
3, 4, 5
b = a[3:6]

Answer Source

With a list comprehension:

>>> [(i, i+len(b)) for i in range(len(a)) if a[i:i+len(b)] == b]
[(3, 6)]

Or with a for-loop:

>>> indexes = []
>>> for i in range(len(a)):
...    if a[i:i+len(b)] == b:
...        indexes.append((i, i+len(b)))
>>> indexes
[(3, 6)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download