Test whether list A is contained in list B
Use any
with list slicing:
def contained_in(lst, sub):
n = len(sub)
return any(sub == lst[i:i+n] for i in range(len(lst)-n+1))
Or, use join
to join both lists to strings and use in
operator:
def contained_in(lst, sub):
return ','.join(map(str, sub)) in ','.join(map(str, lst))
Usage:
>>> contained_in([1, 2, 3, 4, 5], [2, 3, 4])
True
>>> contained_in([1, 2, 2, 4, 5], [2, 3, 4])
False
many people have posted their answers. but I want to post my efforts anyway ;) this is my code:
def containedin(a,b):
for j in range(len(b)-len(a)+1):
if a==b[j:j+len(a)]:
return True
return False
print(containedin([2, 3, 4],[1, 2, 3, 4, 5]))
print(containedin([2, 3, 4],[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]))
print(containedin([2, 3, 4],[5, 4, 3, 2, 1]))
print(containedin([2, 2, 2],[1, 2, 3, 4, 5]))
print(containedin([2, 2, 2],[1, 1, 1, 2, 2, 2, 3, 3, 3]))
this is the output: True False False False True
Assuming a
always shorter than b
what you can do is as follows.
any(a == b[i:i+len(a)] for i in range(len(b)-len(a)+1))