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:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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 settest_set = {6, 4, 2, 7, 9, 1} # printing original setprint("The original set is : " + str(test_set)) # initializing listtest_list = [6, 8, 10] # any() checking for any set element in check listres = any(ele in test_set for ele in test_list) # printing resultprint("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 ? : TrueMethod #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 settest_set = {6, 4, 2, 7, 9, 1} # printing original setprint("The original set is : " + str(test_set)) # initializing listtest_list = [6, 8, 10] # & operator checks for any common elementres = bool(test_set & set(test_list)) # printing resultprint("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

