Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check If Value Exists in Python List of Objects
Next article icon

Python | Check if element exists in list of lists

Last Updated : 15 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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)



Next Article
Check If Value Exists in Python List of Objects
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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
  • Python | Find common elements in list of lists
    The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists. Let's discuss certain ways in which this operation can be
    6 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 - Check if previous element is smaller in List
    Sometimes, while working with Python lists, we can have a problem in which we need to check for each element if its preceding element is smaller. This type of problem can have its use in data preprocessing domains. Let's discuss certain problems in which this task can be performed. Input : test_list
    5 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 front digit is Odd in list
    Sometimes we may face a problem in which we need to find a list if it contains numbers that are odd. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1 : Using list comprehension + map() We can approach this pro
    7 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
  • How to Check if an Index Exists in Python Lists
    When working with lists in Python, sometimes we need to check if a particular index exists. This is important because if we try to access an index that is out of range, we will get an error. Let's look at some simple ways to check if an index exists in a Python list. The easiest methods to check if
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences