Search code examples
pythonlistcomparisoncomparison-operators

Finding a sequence in list using another list In Python


I have a list = [0, 0, 7] and I when I compare it against anotherList = [0, 0, 7, 0] using in it gives me False.

I would like to know how I can check if numbers in one list are in the same sequence as another list.

So, if I do anotherList2 = [7, 0, 0, 0]:

list in anotherList2 returns False

But, list in anotherList return True


Solution

  • Here's a one-liner function that will check if list a is in list b:

    >>> def list_in(a, b):
    ...     return any(map(lambda x: b[x:x + len(a)] == a, range(len(b) - len(a) + 1)))
    ...
    >>> a = [0, 0, 7]
    >>> b = [1, 0, 0, 7, 3]
    >>> c = [7, 0, 0, 0]
    >>> list_in(a, b)
    True
    >>> list_in(a, c)
    False
    >>>