How to test if a list contains another list as a contiguous subsequence?
Solution 1:
If all items are unique, you can use sets.
>>> items = set([-1, 0, 1, 2])
>>> set([1, 2]).issubset(items)
True
>>> set([1, 3]).issubset(items)
False
Solution 2:
There's an all()
and any()
function to do this.
To check if big
contains ALL elements in small
result = all(elem in big for elem in small)
To check if small
contains ANY elements in big
result = any(elem in big for elem in small)
the variable result would be boolean (TRUE/FALSE).
Solution 3:
Here is my version:
def contains(small, big):
for i in xrange(len(big)-len(small)+1):
for j in xrange(len(small)):
if big[i+j] != small[j]:
break
else:
return i, i+len(small)
return False
It returns a tuple of (start, end+1)
since I think that is more pythonic, as Andrew Jaffe points out in his comment. It does not slice any sublists so should be reasonably efficient.
One point of interest for newbies is that it uses the else clause on the for statement - this is not something I use very often but can be invaluable in situations like this.
This is identical to finding substrings in a string, so for large lists it may be more efficient to implement something like the Boyer-Moore algorithm.
Note: If you are using Python3, change xrange
to range
.