Here are four ways to check if a set contains an element in Python:
- Using in operator
- Using not in operator
- Using combination of Counter() and dict.keys()
- Using operator.countOf()
Method 1: Using in operator
You can use the in keyword to test if an element is present in the set, which returns True if the set contains the specified element and False otherwise.
main_set = {11, 19, 21}
is_contain = 19 in main_set
print(is_contain)
Output
True
Check for element 46 in the existing Set and see the output.
main_set = {11, 19, 21}
is_contain = 46 in main_set
print(is_contain)
Output
False
Method 2: Using not in operator
The not in operator works the opposite way as the in operator works precisely. It returns True if the element is not in the set, and False otherwise.
main_set = {11, 19, 21}
is_contain = 46 not in main_set
print(is_contain)
Output
True
Let’s take an example where the element exists in the Set and see the output.
main_set = {11, 19, 21}
is_contain = 11 not in main_set
print(is_contain)
Output
False
Method 3: Using combination of Counter() and dict.keys()
The Counter is a dict subclass from collections module method, used to count the occurrences of elements in an iterable. It is particularly useful for counting elements, especially when dealing with a large number of elements.
from collections import Counter
main_set = {11, 19, 21}
element_dict = Counter(main_set)
print(21 in element_dict.keys())
print(20 in element_dict.keys())
Output
True
False
Method 4: Using operator.countOf()
The operator.countOf() method is used to counts the number of occurrences of an item in an iterable.
import operator as op
main_set ={11, 19, 21}
print(op.countOf(main_set, 19) > 0)
print(op.countOf(main_set, 30) > 0)
Output
True
False
Conclusion
The best and most efficient way to check if a set contains an element is to use the in operator.