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 appraoches to solve the problem.
Approach #1 : Naive Appraoch
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.
- Python | Find maximum length sub-list in a nested list
- Python | Pair and combine nested list to tuple list
- Python | Convert a nested list into a flat list
- Python | Convert given list into nested list
- Python | Intersection of two nested list
- Python | How to copy a nested list
- Nested List Comprehensions in Python
- Python | Remove duplicates from nested list
- Python | Remove all occurrences in nested list
- Python | Split nested list into two lists
- Python | Column wise sum of nested list
- Python | Remove all duplicates and permutations in nested list
- Python | Find the sublist with maximum value in given nested list
- Python | Convert list of nested dictionary into Pandas dataframe
- Python | Check if one list is subset of other
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.