Search code examples
pythonlistpython-itertools

How to check subsequence exists in a list?


In python, it's possible to use the is keyword to check for contains, e.g.

>>> 3 in [1,2,3,4,5]
True

But this doesn't yield the same output if it's checking whether a list of a single integer is inside the reference list [1,2,3,4,5]:

>>> [3] in [1,2,3,4,5]
False

Also, checking a subsequence in the reference list cannot be achieved with:

>>> [3,4,5] in [1,2,3,4,5]
False

Is there a way to have a function that checks for subsequence such that the following returns true? e.g. a function call x_in_y():

>>> x_in_y([3,4,5], [1,2,3,4,5])
True
>>> x_in_y([3], [1,2,3,4,5])
True
>>> x_in_y(3, [1,2,3,4,5])
True
>>> x_in_y([2,3], [1,2,3,4,5])
True
>>> x_in_y([2,4], [1,2,3,4,5])
False
>>> x_in_y([1,5], [1,2,3,4,5])
False

Maybe something from itertools or operator?

(Note, the input lists can be non-unique)


Solution

  • x_in_y() can be implemented by slicing the original list and comparing the slices to the input list:

    def x_in_y(query, base):
        try:
            l = len(query)
        except TypeError:
            l = 1
            query = type(base)((query,))
    
        for i in range(len(base)):
            if base[i:i+l] == query:
                return True
        return False
    

    Change range to xrange if you are using Python2.