Python | Check if a list is contained in another list
Given two lists A and B, write a Python program to Check if list A is contained in list B without breaking A’s order.
Examples:
Input : A = [1, 2], B = [1, 2, 3, 1, 1, 2, 2] Output : True Input : A = ['x', 'y', 'z'], B = ['x', 'a', 'y', 'x', 'b', 'z'] Output : False
Approach #1 : Naive Approach
A simple naive approach is to use two for loops and check if the whole list A is contained within list B or not. If such a position is met in list A, then break the loop and return true, otherwise false
# Python3 program to Check if a list is # contained in another list without breaking order def removeElements(A, B): for i in range ( len (B) - len (A) + 1 ): for j in range ( len (A)): if B[i + j] ! = A[j]: break else : return True return False # Driver code A = [ 1 , 2 ] B = [ 1 , 2 , 3 , 1 , 1 , 2 , 2 ] print (removeElements(A, B)) |
True
Approach #2 : List comprehension
A more efficient approach is to use List comprehension. We first initialize ‘n’ with length of A. Now use a for loop till len(B)-n and check in each iteration if A == B[i:i+n]
or not.
# Python3 program to Remove elements of # list that repeated less than k times def removeElements(A, B): n = len (A) return any (A = = B[i:i + n] for i in range ( len (B) - n + 1 )) # Driver code A = [ 1 , 2 ] B = [ 1 , 2 , 3 , 1 , 1 , 2 , 2 ] print (removeElements(A, B)) |
True
Approach #3 : Using join and map module
Here we use join to join both lists to strings and then use in operator to check if list A is contained in B or not.
# Python3 program to Remove elements of # list that repeated less than k times def removeElements(A, B): return ', ' .join( map ( str , A)) in ', ' .join( map ( str , B)) # Driver code A = [ 'x' , 'y' , 'z' ] B = [ 'x' , 'a' , 'y' , 'x' , 'b' , 'z' ] print (removeElements(A, B)) |
False