Python | Check if element exists in list of lists
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 listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]]elem_to_find = 8elem_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 resultprint(str(res1), "\n", str(res2)) |
Output:
True False
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 listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]]elem = 8elem1 = 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 resultprint(str(res1), "\n", str(res2)) |
Output:
True False
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 listfrom itertools import chain# initialising nested listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]]elem_to_find = 8elem_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 resultprint(str(res1), "\n", str(res2)) |
Output:
True False
Method #4: Using extend() method and in operator
Python3
# Python code to demonstrate# finding whether element# exists in listof list# initialising nested listsini_list = [[1, 2, 5, 10, 7], [4, 3, 4, 3, 21], [45, 65, 8, 8, 9, 9]]elem = 8elem1 = 0# element exists in listof listor not?res1 = Falseres2 = Falsex = []for i in ini_list: x.extend(i)if elem in x: res1 = Trueif elem1 in x: res2 = True# printing resultprint(str(res1))print(str(res2)) |
Output
True False





Please Login to comment...