There are multiple methods that can be used to check whether a list exists in another list of lists. We will explain them one by one in this post.
In Python, you can use the "in" keyword to check if a list exists in a list of lists. For example, if you have a list of lists called "my_list", you can use the "in" keyword to check if the list "my_list" contains the list "my_sub_list".
Syntax
list in list_of lists
Code example
my_list = [[10, 20], [10, 30, 40], [50, 60], [20, 30]]
my_sub_list = [50, 60]
if my_sub_list in my_list:
print("Sublist exists")
else:
print("Sublist does not exist")
Output
Sublist exists
The order of items in the sub list must be the same as the order of the child list in the master list to check whether a list exists in a list of lists using the 'in' keyword.
In Python, the Counter() function is used to keep track of how many times an element appears in a list. It is a part of the collections module. This function is especially useful when you have a list of lists. For example, if you have a list of numbers, you can use the Counter() function to check if a list exists in another list of lists.
import collections
main_lists = [[10, 20], [10, 30, 40], [50, 60], [20, 30]]
sub_list = [50, 60]
for lst in main_lists:
if collections.Counter(lst) == collections.Counter(sub_list):
print("sub list exist")
else:
print("not exist")
Output
sub list exist
In the above code example:
0 Comments