Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly.
Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False
Let’s discuss few approaches to solve the problem.
Approach #1 : Naive Approach
Take a variable ‘exist’ which keeps track of each element, whether it is present in list1 or not. Start a loop and in each iteration ‘i’, check if ith element is present in list1. If present, set exist to True else false.
Approach #2 : Using Python set
Convert each sublist of both the given nested lists to tuples, because sets can’t hold lists as they rely on their elements being immutable and lists are mutable. But converting them to tuple works well. After this, simply check if set of list2 is a subset of list1 or not.
Approach #3 : Using all and for loop
This method uses a for loop to check if all elements(using all) belongs to list1 or not.
Approach #4 : Using
In this approach we use Python
map() using the “containment check” operator __contains__, checking whether list1 elements are contained withing list2 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.
- SymPy | Subset.subset() in Python
- Python - Nested Dictionary Subset
- Python | Test if string is subset of another
- Python | Check if a list is contained in another list
- Python | Check if one list is subset of other
- Python | Pair and combine nested list to tuple list
- Python | Convert a nested list into a flat list
- Python | Find maximum length sub-list in a nested list
- Python | Convert given list into nested list
- Python | Convert string List to Nested Character List
- Python | Check if one dictionary is subset of other
- Python | Check if one tuple is subset of other
- 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 | Sectional subset sum in list
- Nested List Comprehensions in Python
- Python | Intersection of two nested list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.
Improved By : shubham_singh