Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeing if a list exists within another list?

Tags:

python

list

Basically lets say i have:

>>> a = [1,3,2,2,2]
>>> b = [1,3,2]

I want to see if the all the elements in b, exists within a, and in the same order. So for the above example b would exist within a.

I am kinda hoping theres a really simple one line answer.

like image 690
UberJumper Avatar asked Dec 11 '25 06:12

UberJumper


2 Answers

This is a simple O(n * m) algorithm:

any(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))

Note that is not the fastest way of doing this. If you need high performance you could use similar techniques to those used in string searching algorithms.

like image 128
Mark Byers Avatar answered Dec 12 '25 20:12

Mark Byers


If by 'in the same order' you meant subsequence (as opposed to substring) then this non-one-liner should work fast:

  def is_subsequence(x, y):
    i, j = 0, 0
    while i < len(x) and j < len(y):
      if x[i] == y[j]:
        i += 1
      j += 1
    return i == len(x)