Ra S
Ra S

Reputation: 11

Check if a list is part of another list while preserving the list sequence

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

Answers (2)

shreyas labhsetwar
shreyas labhsetwar

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

Elisha
Elisha

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 ith 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

Related Questions