Here is an iterative version of a method using index given by Triptych. I think this is probably the best way to do this, since index should be faster than any manual indexing or iteration:
def test(lst1, lst2): start = 0 try: for item in lst1: start = lst2.index(item, start) + 1 except ValueError: return False return True
In Python, it should work much better than the recursive version. It also correctly adds one to the starting point after each search so as not to give false positives when there are duplicates in the first list.
Here are two solutions that primarily repeat on top of lst2 instead of lst1 , but are otherwise similar to the jedwards version.
The first is simple and uses indexing, but only indexes, when you actually move to another element in lst1 , and not to each element in lst2 :
def test(lst1, lst2): length, i, item = len(lst1), 0, lst1[0] for x in lst2: if x == item: i += 1 if i == length: return True item = lst1[i] return False
The second uses manual iteration over lst1 with next instead of indexing:
def test(lst1, lst2): it = iter(lst1) try: i = next(it) for x in lst2: if x == i: i = next(it) except StopIteration: return True return False
Both are probably small enhancements as they reduce indexing and do not need to build a range for each element in lst1 .
source share