You can use all() by performing the check for membership of a in b through an iterator on b:
a = [1,1,2]
b = [0, 1,1,1,2,1]
r = all(n in ib for ib in [iter(b)] for n in a)
print(r) # True
It will also find a match for items in the same relative order (that are not consecutive):
a=[1,2,1]
b=[1,2,3,1]
r = all(n in ib for ib in [iter(b)] for n in a)
print(r) # True
How it works:
- every time
n in ib is executed, the ib iterator advances up to the next matching value in b.
- Going through all values of
a will match items sequentially over the remainder of b after each match check
- If
ib is exhausted before getting to the end of a, then the elements aren't all present or their order doesn't match
If you are looking for consecutive matches, you can use the in operator on a generator that yields sublists of the corresponding length:
a = [1,1,2]
b = [0, 1,1,1,2,1]
r = a in (b[i:i+len(a)] for i in range(len(b)-len(a)+1))
print(r) # True