Reputation: 11
How to check if a list in python is part of another list with preserving the order. Example:
a = [3, 4, 1, 2, 5]
b = [4, 1, 2]
Answer is True
a = [3, 4, 1, 0, 2, 5]
b = [4, 1, 2]
Answer is False as the order is not matched
Upvotes: 0
Views: 277
Reputation: 53
Use this function:
def is_a_in_x(A, X):
for i in range(len(X) - len(A) + 1):
if A == X[i:i+len(A)]: return True
return False
Upvotes: 0
Reputation: 23770
This can be solved using python lists equality, comparing the sublists at all positions:
is_b_sublist_of_a = any(b == a[i:i+len(b)] for i in range(len(a)))
The expression a[i:i+len(b)]
creates a list at the length of b
starting from the i
th position. This expression is computed for all positions in a
. If any of the comparisons return True
, the any
expression will be True
as well, and False
otherwise.
Upvotes: 1