Check if a list exists in given list of lists in Python


Lists can be nested, means the elements of a list are themselves lists. In this article we will see how to find out if a given list is present as an element in the outer bigger list.

With in

This is a very simple and straight forward method. We use the in clause just to check if the inner list is present as an element in the bigger list.

Example

 Live Demo

listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_list = [-4,434,0]

# Given list
print("Given List :\n", listA)
print("list to Search: ",search_list)

# Using in
if search_list in listA:
print("Present")
else:
print("Not Present")

Output

Running the above code gives us the following result −

Given List :
[[-9, -1, 3], [11, -8], [-4, 434, 0]]
list to Search: [-4, 434, 0]
Present

With any

We can also use the any clause where we take an element and test if it is equal to any element present in the list. Of course with help of a for loop.

Example

 Live Demo

listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_list = [-4,434,0]

# Given list
print("Given List :\n", listA)
print("list to Search: ",search_list)

# Using in
if any (x == search_list for x in listA):
print("Present")
else:
print("Not Present")

Output

Running the above code gives us the following result − 

Given List :
[[-9, -1, 3], [11, -8], [-4, 434, 0]]
list to Search: [-4, 434, 0]
Present

Updated on: 13-May-2020

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements