How can I test if a list contains another list (ie. it's a contiguous subsequence). Say there was a function called contains:
contains([1,2], [-1, 0, 1, 2]) # Returns [2, 3] (contains returns [start, end])
contains([1,3], [-1, 0, 1, 2]) # Returns False
contains([1, 2], [[1, 2], 3]) # Returns False
contains([[1, 2]], [[1, 2], 3]) # Returns [0, 0]
Edit:
contains([2, 1], [-1, 0, 1, 2]) # Returns False
contains([-1, 1, 2], [-1, 0, 1, 2]) # Returns False
contains([0, 1, 2], [-1, 0, 1, 2]) # Returns [1, 3]
If all items are unique, you can use sets.
There's an
all()
andany()
function to do this. To check if list1 contains ALL elements in list2To check if list1 contains ANY elements in list2
the variable result would be boolean (TRUE/FALSE).
The problem of most of the answers, that they are good for unique items in list. If items are not unique and you still want to know whether there is an intersection, you should count items:
You can also return the intersection by using
''.join(list1&list2)
I think this one is fast...
May I humbly suggest the Rabin-Karp algorithm if the
big
list is really big. The link even contains almost-usable code in almost-Python.This works and is fairly fast since it does the linear searching using the builtin
list.index()
method and==
operator: