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:
Python - Test if all elements in list are of same type
Next article icon

Python - Test if any set element exists in List

Last Updated : 27 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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}, test_list = [6, 8, 10]

Output : False

Explanation : No set element exists in list.

Method #1 : Using any()

In this, we iterate for all the elements of the set and check if any occurs in the list. The any(), returns true for any element matching condition.

Python3
# Python3 code to demonstrate working of # Test if any set element exists in List # Using any()  # initializing set test_set = {6, 4, 2, 7, 9, 1}  # printing original set print("The original set is : " + str(test_set))  # initializing list test_list = [6, 8, 10]  # any() checking for any set element in check list res = any(ele in test_set for ele in test_list)  # printing result print("Any set element is in list ? : " + str(res)) 

Output:

The original set is : {1, 2, 4, 6, 7, 9} Any set element is in list ? : True

Time complexity: O(n) where n is the length of test_list. 
Auxiliary space: O(1). The memory used by the program is constant and does not increase with the size of the input.

Method #2 : Using & operator

In this, we check for any element by using and operation between set and list, if any element matches, the result is True.

Python3
# Python3 code to demonstrate working of # Test if any set element exists in List # Using & operator  # initializing set test_set = {6, 4, 2, 7, 9, 1}  # printing original set print("The original set is : " + str(test_set))  # initializing list test_list = [6, 8, 10]  # & operator checks for any common element res = bool(test_set & set(test_list))  # printing result print("Any set element is in list ? : " + str(res)) 

Output:

The original set is : {1, 2, 4, 6, 7, 9} Any set element is in list ? : True

Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(m), where m is the length of the test_set converted to a set.

Method #3:Using Counter()+lambda functions

Python3
# Python3 code to demonstrate working of # Test if any set element exists in List from collections import Counter  # initializing set test_set = {6, 4, 2, 7, 9, 1}  # printing original set print("The original set is : " + str(test_set))  # initializing list test_list = [6, 8, 10]  freq = Counter(test_list) res = len(list(filter(lambda x: x in freq.keys(), test_set))) > 0  # printing result print("Any set element is in list ? : " + str(res)) 

Output
The original set is : {1, 2, 4, 6, 7, 9} Any set element is in list ? : True

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

Method#4: using set intersection

Algorithm:

  1. Initialize the test_set and test_list.
  2. Use set intersection() method to check if there is any element present in both sets.
  3. The intersection() method returns a set of common elements between the two sets.
  4. Check if the returned set is empty or not using the bool() function.
  5. Print the result.
Python3
# Initializing set test_set = {6, 4, 2, 7, 9, 1}  # printing original set print("The original set is : " + str(test_set))  # initializing list test_list = [6, 8, 10]  # checking for any set element in check list using set intersection res = bool(test_set.intersection(test_list))  # printing result print("Any set element is in list ? : " + str(res)) 

Output
The original set is : {1, 2, 4, 6, 7, 9} Any set element is in list ? : True

Time Complexity:
The time complexity of the set intersection() method is O(min(len(test_set), len(test_list))), as it iterates over the smaller set to check the common elements. So the overall time complexity of the code is O(min(len(test_set), len(test_list))).

Auxiliary Space:
The set intersection() method creates a set of common elements, which takes extra space. However, the space required by this set is proportional to the number of common elements between the two sets. So the auxiliary space complexity of the code is O(min(len(test_set), len(test_list))).


Next Article
Python - Test if all elements in list are of same type
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python set-programs
Practice Tags :
  • python

Similar Reads

  • Extract Elements from list in set - Python
    We are given a list and our task is to extract unique elements from list in a set. For example: a = [1, 2, 3, 4, 5, 2, 3, 6] here we would only extract those elements from list which are unique hence resultant output would be {1,2,3,4,5,6}. Using Set Conversion In this method we convert the list int
    2 min read
  • Python - Test if all elements in list are of same type
    When working with lists in Python, there are times when we need to ensure that all the elements in the list are of the same type or not. This is particularly useful in tasks like data analysis where uniformity is required for calculations. In this article, we will check several methods to perform th
    3 min read
  • Python - Test if string contains element from list
    Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string. Using any() with a generator expressionany() is the most efficient way to check if any element from the list is present in the list. [GFGTABS] Python s = "Pyth
    3 min read
  • Test if all elements are present in list-Python
    The task of testing if all elements are present in a list in Python involves checking whether every item in a target list exists within a reference list. For example, given two lists a = [6, 4, 8, 9, 10] and b = [4, 6, 9], the task is to confirm that all elements in list b are also found in list a.
    3 min read
  • 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. C/C++ Code # Python code to dem
    5 min read
  • Python - Test if tuple list has Single element
    Given a Tuple list, check if it is composed of only one element, used multiple times. Input : test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Output : True Explanation : All elements are equal to 3. Input : test_list = [(3, 3, 3), (3, 3), (3, 4, 3), (3, 3)] Output : False Explanation : All elemen
    8 min read
  • Find Common elements in three Lists using Sets - Python
    We are given three lists we need to find common elements in all three lists using sets. For example a = [1, 2, 3, 4], b = [2, 3, 5, 6] and c = [1, 2, 3, 7]. We need to find all common elements so that resultant output should be {2, 3}. Using set.intersection()set.intersection() method finds common e
    3 min read
  • Time Complexity for Adding Element in Python Set vs List
    Adding elements differs due to their distinct underlying structures and requirements for uniqueness or order. Let's explore and compare the time complexity by adding elements to lists and sets. In this article, we will explore the differences in time complexities between a Set and a List if we add a
    2 min read
  • Checking Element Existence in a Python Set
    We are given a set and our task is to check if a specific element exists in the given set. For example, if we have s = {21, 24, 67, -31, 50, 11} and we check for the element 21, which is present in the set then the output should be True. Let's explore different ways to perform this check efficiently
    2 min read
  • Python - Check if all elements in List are same
    To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. [GFGTABS] Python a = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) [/GFGTABS]OutputTrue Ex
    3 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