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 Appraoch
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
Recommended Posts:
- Python | Check if a list exists in given list of lists
- Python | Check if a nested list is a subset of another nested list
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Check if a given object is list or not
- Python | Check if list is Matix
- Python | Check if all elements in a List are same
- Python | Check if all the values in a list are less than a given value
- Python | Check if list is sorted or not
- Python | Check whether a list is empty or not
- Python | Check if one list is subset of other
- Python | Check if given words appear together in a list of sentence
- Python | Check if all elements in a list are identical
- Python | Check if list is strictly increasing
- Python | Check if list contains all unique elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



