# 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 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))`

Output:

```True
False```

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))`

Output:

```True
False```

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))`

Output:

```True
False```

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))`

Output

```True
False```

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`

Output

```True
False```

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 :

1. Initialize a list of lists lst, an empty list lst1, and a target element n.
2. Iterate over each sublist in lst and append its elements to lst1.
3. Use the Counter() function to count the frequency of each element in lst1.
4. Check if the frequency of the target element n in lst1 is greater than 0.
5. 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`

Output

```exist
```

Time Complexity : O(n)
Auxiliary Space : O(1)

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next