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.
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.
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.
- Retrieving And Updating Data Contained in Shelve in Python
- Python | Check if a nested list is a subset of another nested list
- PyQt5 - Check box checked state depending upon another check box
- Python | Insert list in another list
- Python | Update a list of tuples using another list
- Python | Move one list element to another list
- Python program to get the indices of each element of one list in another list
- Python - Group Sublists by another List
- Python - Sum of each List element occurrence in another
- Check if a string can be repeated to make another string
- Python | Remove sublists that are present in another sublist
- Python | Add one string to another
- Python | Raising an Exception to Another Exception
- Python | Sorting string using order defined by another string
- Python | How to copy data from one excel sheet to another
- Python - Raise elements of tuple as power to another tuple
- Python - Call function from another function
- Python - Call function from another file
- Python | Test if string is subset of another
- Python - Append content of one text file to another
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Improved By : ManasChhabra2