Python | Check if element exists in list of lists
Last Updated :
15 May, 2023
Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task.
Method #1: Using any() any() method return true whenever a particular element is present in a given iterator.
Python3
# Python code to demonstrate
# finding whether element
# exists in listof list
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem_to_find = 8
elem_to_find1 = 0
# element exists in listof listor not?
res1 = any(elem_to_find in sublist for sublist in ini_list)
res2 = any(elem_to_find1 in sublist for sublist in ini_list)
# printing result
print(str(res1), "\n", str(res2))
Time complexity: O(n) where n is the number of elements in all the sublists combined.
Auxiliary space: O(1), as we are using a single variable "res1" and "res2" to store the result.
Method #2: Using operator in The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise.
Python3
# Python code to demonstrate
# finding whether element
# exists in listof list
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem = 8
elem1 = 0
# element exists in listof listor not?
res1 = elem in (item for sublist in ini_list for item in sublist)
res2 = elem1 in (item for sublist in ini_list for item in sublist)
# printing result
print(str(res1), "\n", str(res2))
Time complexity: O(n) where n is the total number of elements in the nested lists.
Auxiliary space: O(1) as it only requires a few variables and does not use any data structures to store any intermediate results
Method #3: Using itertools.chain()
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.
Python3
# Python code to demonstrate
# finding whether element
# exists in listof list
from itertools import chain
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem_to_find = 8
elem_to_find1 = 0
# element exists in listof listor not?
res1 = elem_to_find in chain(*ini_list)
res2 = elem_to_find1 in chain(*ini_list)
# printing result
print(str(res1), "\n", str(res2))
Time complexity: O(n), where n is the total number of elements in the nested list.
Auxiliary space: O(1).
Method #4: Using extend() method and in operator
Python3
# Python code to demonstrate
# finding whether element
# exists in listof list
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem = 8
elem1 = 0
# element exists in listof listor not?
res1 = False
res2 = False
x = []
for i in ini_list:
x.extend(i)
if elem in x:
res1 = True
if elem1 in x:
res2 = True
# printing result
print(str(res1))
print(str(res2))
Time complexity: O(n*m), where n is the number of lists and m is the maximum length of any list.
Auxiliary space: O(n*m), as we are creating a new list by extending all the sublists in the initial list.
Method #5: Using functools.reduce():
Another approach to check if an element exists in a list of lists is to use the functools.reduce() function. The functools.reduce() function applies a function to a list of elements in a cumulative manner, returning a single result.
For example:
Python3
import functools
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem_to_find = 8
elem_to_find1 = 0
# element exists in listof list or not?
res1 = functools.reduce(lambda x, y: x or y, [elem_to_find in sublist for sublist in ini_list])
res2 = functools.reduce(lambda x, y: x or y, [elem_to_find1 in sublist for sublist in ini_list])
# printing result
print(res1)
print(res2)
#This code is contributed by Edula Vinay Kumar Reddy
This approach iterates over each sublist in the list of lists and checks if the element to be searched for is present in that sublist using the in operator. The result of this check for each sublist is passed to the functools.reduce() function, which applies the or operator in a cumulative manner to the elements in the list. If any element in the list is True, the functools.reduce() function will return True, otherwise it will return False. This allows you to check if the element is present in any of the sublists in the list of lists.
Time complexity: O(N) where n is the length all the elements in list
Auxiliary Space: O(1)
Method#6 : Using counter()
Algorithm :
- Initialize a list of lists lst, an empty list lst1, and a target element n.
- Iterate over each sublist in lst and append its elements to lst1.
- Use the Counter() function to count the frequency of each element in lst1.
- Check if the frequency of the target element n in lst1 is greater than 0.
- If the frequency of n is greater than 0, output "exist", otherwise output "not exist".
Python3
#python program to check given element exist in the list of list or not
#Initializing the values
from collections import Counter
lst=[[3, 4], [2, 0],[6,8]]
lst1=[]
n=3
for i in range(0,len(lst)):
for j in lst[i]:
lst1. append(j)
#checking for element 3 using Counter()
freq=Counter(lst1)
if freq[n]>0:
print('exist')
else:
print ('not exist')
#This code is contributed by SHAIK HUSNA
Time Complexity : O(n)
Auxiliary Space : O(1)
Similar Reads
Python | Check if a list exists in given list of lists 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
4 min read
Check If Value Exists in Python List of Objects When working with Python, we might need to check whether a specific value exists in a list of objects. This problem often arises when dealing with data stored as objects and we want to verify the presence of a specific property value. Using any() Function with List Comprehensionany() function is an
4 min read
Python - Test if any set element exists in List Given a set and list, the task is to write a python program to check if any set element exists in the list. Examples: Input : test_dict1 = test_set = {6, 4, 2, 7, 9, 1}, test_list = [6, 8, 10] Output : True Explanation : 6 occurs in list from set. Input : test_dict1 = test_set = {16, 4, 2, 7, 9, 1},
4 min read
Python - Check if any list element is present in Tuple Given a tuple, check if any list element is present in it. Input : test_tup = (4, 5, 10, 9, 3), check_list = [6, 7, 10, 11] Output : True Explanation : 10 occurs in both tuple and list. Input : test_tup = (4, 5, 12, 9, 3), check_list = [6, 7, 10, 11] Output : False Explanation : No common elements.
6 min read
Python - Check if element is present in tuple We are given a tuple and our task is to find whether given element is present in tuple or not. For example x = (1, 2, 3, 4, 5) and we need to find if 3 is present in tuple so that in this case resultant output should be True.Using in Operatorin operator checks if an element is present in a tuple by
2 min read
Python Check if the List Contains Elements of another List The task of checking if a list contains elements of another list in Python involves verifying whether all elements from one list are present in another list. For example, checking if ["a", "b"] exists within ["a", "b", "c", "d"] would return True, while checking ["x", "y"] would return False. Using
3 min read