Check if Range element exists in Set using Python

By | November 29, 2024

Given a set, test if any element from range exists in set.

Input : test_set = {1, 5, 2, 7, 3, 4, 10, 14}, strt, end = 8, 12
Output : True 
Explanation : 10 is in range and present in set, hence True.

Input : test_set = {1, 5, 2, 7, 3, 4, 15, 14}, strt, end = 8, 12
Output : False
Explanation : No element in range is present.

Method #1 : Using any()
In this, each element is iterated from range to check for existence in set. The any() is used to check if any of range element is found.

# Python3 code to demonstrate working of
# Test if any range element exists in set
# Using any()

# initializing strings set
test_set = {1, 5, 2, 7, 3, 4, 10, 14}

# printing original string
print("The original set is : " + str(test_set))

# initializing range 
strt, end = 8, 12 

# any() tests for all the elements in range
# range() creates range
res = any(ele in test_set for ele in range(strt, end))

# printing result
print("Does range element exists ? : " + str(res))

Output

The original set is : {1, 2, 3, 4, 5, 7, 10, 14}
Does range element exists ? : True

Method #2 : Using set.intersection() + bool()
In this, intersection of elements from range is tested using intersection(), and bool() is used get the presence of any element, to know set is not empty.

# Python3 code to demonstrate working of
# Test if any range element exists in set
# Using set.intersection() + bool()

# initializing strings set
test_set = {1, 5, 2, 7, 3, 4, 10, 14}

# printing original string
print("The original set is : " + str(test_set))

# initializing range 
strt, end = 8, 12 

# intersection() gets the set intersection with range
# range() creates range
res = bool(test_set.intersection(range(strt, end)))

# printing result
print("Does range element exists ? : " + str(res))

Output

The original set is : {1, 2, 3, 4, 5, 7, 10, 14}
Does range element exists ? : True
Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.