python

Check if a list exists in a list of lists Python

A list of lists is a data structure that stores an ordered collection of items, where each item is a list itself. This is a powerful way to store data in Python, but it can be tricky to work with if you're not familiar with it. In this article, we'll show you how to check if a list exists in a list of lists, and how to access it if it does.

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.

Method 1: Using python 'in' keyword

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
  1. This code checks whether a sublist exists in a given list.my_list contains a list of lists.
  2. my_sub_list is a list that we are checking to see if it exists in my_list.If my_sub_list is found in my_list, the code will print "Sublist exists".
  3. If my_sub_list is not found in my_list, the code will print "Sublist does not exist".

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.

Method 2: Using Counter() function of collection module

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:

  1. import the collections module.
  2. Create a main_lists variable, which contains a list of lists.
  3. Create a sub_list variable, which contains a list.
  4. Iterate through each list in main_lists.
  5. Compare the collections.Counter() of each list in main_lists to the collections.Counter() of sub_list.
  6. if they are equal, print "sub list exist".
  7. If they are not equal, print "not exist".
Was this helpful?