Definition:
- List A is a sublist of list B if the exact sequence of elements of A exists in B.
- An empty list is a sublist of any list.
The following function returns the index of the first occurrence of list_a
in list_b
, otherwise -1
is returned. For empty list_a
, 0
is returned.
def sublist(list_a, list_b):
if 0 == len(list_a):
return 0
if len(list_b) < len(list_a):
return -1
idx = -1
while list_a[0] in list_b[idx+1:]:
idx = list_b.index(list_a[0], idx + 1)
if list_a == list_b[idx:idx+len(list_a)]:
return idx
return -1
Some tests:
>>> sublist([], [])
0
>>> sublist([], [1, 2, 3])
0
>>> sublist([3, 6], [1, 2, 3, 6, 3, 7, 9, 8, 0, 3, 6])
2
>>> sublist([3, 7, 9, 8], [1, 2, 3, 6, 3, 7, 9, 8, 0, 3, 6])
4
>>> sublist([3, 6, 3, 7, 9, 8, 0, 3, 6], [1, 2, 3, 6, 3, 7, 9, 8, 0, 3, 6])
2
>>> sublist([1, 2, 3, 6, 3, 7, 9, 8, 0, 3, 6, 4], [1, 2, 3, 6, 3, 7, 9, 8, 0, 3, 6])
-1
>>> sublist([3, 7, 4], [1, 2, 3, 6, 3, 7, 9, 8, 0, 3, 6])
-1