Given a list of lists, the task is to check if a list exists in given list of lists.
Input :
lst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]
list_search = [4, 5, 6]
Output: True
Input :
lst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]]
list_search = [4, 12, 54]
Output: False
Let’s discuss certain ways in which this task is performed.
Method #1: Using Counter The most concise and readable way to find whether a list exists in list of lists is using Counter.
Python3
import collections
Input = [[ 1 , 1 , 1 , 2 ], [ 2 , 3 , 4 ], [ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]
list_search = [ 2 , 3 , 4 ]
flag = 0
for elem in Input :
if collections.Counter(elem) = = collections.Counter(list_search) :
flag = 1
if flag = = 0 :
print (" False ")
else :
print (" True ")
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2: Using in
Python3
Input = [[ 1 , 1 , 1 , 2 ], [ 2 , 3 , 4 ], [ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]
list_search = [ 1 , 1 , 1 , 2 ]
if list_search in Input :
print (" True ")
else :
print (" False ")
|
Method #3: Using any
Python3
Input = [[ 1 , 1 , 1 , 2 ], [ 2 , 3 , 4 ], [ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]
list_search = [ 4 , 5 , 6 ]
if any ( list = = list_search for list in Input ):
print (" True ")
else :
print (" False ")
|
Method #4 : Using count() method
Python3
Input = [[ 1 , 1 , 1 , 2 ], [ 2 , 3 , 4 ], [ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]
list_search = [ 2 , 3 , 4 ]
res = False
if ( Input .count(list_search)> = 1 ):
res = True
print (res)
|
Time Complexity: O(n), where n is length of Input list.
Auxiliary Space: O(1)
Method #5: Using all() and any() both
Here is an approach using a list comprehension and the all function:
Python3
lst = [[ 1 , 1 , 1 , 2 ], [ 2 , 3 , 4 ], [ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]
list_search = [ 4 , 5 , 6 ]
result = any ( all (item in sublist for item in list_search) for sublist in lst)
print (result)
|
This would also output True.
The any function returns True if any element in the input iterable is True, and False otherwise. In this case, the list comprehension generates a list of boolean values that indicate whether list_search is contained in each sublist in lst. The any function then returns True if any of these boolean values is True, which indicates that list_search exists in lst.
In terms of time complexity, this approach has a complexity of O(n) since it needs to iterate over all the sublists in lst to check for the presence of list_search. In terms of space complexity, it has a complexity of O(n) since it creates a list of boolean values that is the same size as lst.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Apr, 2023
Like Article
Save Article