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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course