Check if element exists in list of lists in Python

PythonServer Side ProgrammingProgramming

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 element is present in the sublist which are themselves elements in the bigger list.

With any

We first search if an element is present in the sublist and if the sublist is present in the list. If anyof this is true we can say that the element is present in the list.

Example

 Live Demo

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

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

print("Element to Search: ",search_element)

# Using in
if any(search_element in sublist for sublist in listA):
   print("Present")
else:
   print("Not Present")

Output

Running the above code gives us the following result −

('Given List :\n', [[-9, -1, 3], [11, -8], [-4, 434, 0]])
('Element to Search: ', -8)
Present

With in

In this approach we make a simple search using the in operator. If the item is part of sublist which is also a part of the outer list, then we accept the element as present. We make two checks one to check the presence and another to check the absence.

Example

 Live Demo

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

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

print("Element to Search: ",search_element)

# Using in
if search_element in (item for sublist in listA for item in sublist):
   print("Present")
else:
   print("Not Present")

search_element = 13
print("New Element to Search: ",search_element)

# Using in
if search_element in (item for sublist in listA for item in sublist):
   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]]
Element to Search: -8
Present
New Element to Search: 13
Not Present

With chain

With the chain method from itertools module we can expand the lists of sublists and keep checking for the presence of an element using the in menthod.

Example

 Live Demo

from itertools import chain

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

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

print("Element to Search: ",search_element)

# Using in
if search_element in chain(*listA):
   print("Present")
else:
   print("Not Present")

search_element = 13
print("New Element to Search: ",search_element)

# Using in
if search_element in chain(*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]]
Element to Search: -8
Present
New Element to Search: 13
Not Present
raja
Published on 13-May-2020 17:45:46
Advertisements