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.
Using 'in' operator
This is a membership operator used to check whether the given value is present in a set or not. It will return True if the given element is present in the set, otherwise False.
s = {21, 23, '#', "Geeks", "For", -22}
if 21 in s:
print("Element found in the set")
else:
print("Element not found in the set")
print(70 in s)
print("Geeks" in s)
Output
Element found in the set False True
Explanation: 70 in s returns False because the set s doesn't have 70 in it, while "Geeks" in s returns True because the set does contains it.
Using 'not in' operator
This is a membership operator used to check whether the given value is present in set or not. It will return True if the given element is not present in set, otherwise False
s = {21, 23, '#', "Geeks", "For", -22}
print(73 not in s)
print("Geeks" not in s)
Output
True False
Explanation: 73 not in s returns True because the set s doesn't have 73 in it, while "Geeks" not in s returns False because the set does contains it.
Using 'operator.countOf()' method
operator module is imported and aliased as op and the code then uses op.countOf() method to check if specific elements are present in the set data.
import operator as op
s = {21, 23, '#', "Geeks", "For", -22}
print(op.countOf(s, 21) > 0)
print(op.countOf(s, "Geeks") > 0)
Output
True True
Explanation:
- op.countOf(s, 21) checks if 21 is in the set s, and op.countOf(s, "Geeks") does the same for "Geeks". It returns 1 if the value is found otherwise 0.
- in this code the result is converted to True or False by checking if it's greater than 0.
Related Article: