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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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
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.
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.