greeting = ['hello','my','name','is','bob','how','are','you','my','name','is'] def find_sub_list(sl,l): results=[] sll=len(sl) for ind in (i for i,e in enumerate(l) if e==sl[0]): if l[ind:ind+sll]==sl: results.append((ind,ind+sll-1)) return results print find_sub_list(['my','name','is'], greeting) # [(1, 3), (8, 10)]
Here is what the above code is Doing:
1. It’s creating a list of indices where the first element of the sublist is found in the main list.
2. It’s iterating through that list and checking if the sublist is actually a sublist of the main list.
3. It’s appending the indices of the sublist to a results list.
4. It’s returning the results list.