The most Pythonic way to check if an element exists is to use the in operator. Sets provide O(1) average time complexity for membership checks due to their underlying hash table implementation.
The in operator returns True if the set contains an element and False otherwise.
Syntax
element in set
Basic membership check
Let’s declare a Set named “stocks” and check for two different elements, and see if the set contains those elements.
stocks = {"Kaynes", "Dixon", "PGEL"}
print("Kaynes" in stocks)
# Output: True
print("Syrma" in stocks)
# Output: False
Case sensitivity
The in operator checks for case-sensitivity as well. So, lowercase and uppercase make a huge difference.
langs = {"Python", "Php", "JavaScript"}
print("php" in langs)
# Output: False
print("Php" in langs)
# Output: True
Mixed types
What if the set contains different types of elements, and we check for a specific type? If it exists, returns True; otherwise, False.
data = {21, "Krunal", (19, 10)}
print(21 in data)
# Output: True
print("Krunal" in data)
# Output: True
print((19, 21) in data)
# Output: False
print((19, 10) in data)
# Output: True
print([1, 2] in data)
# TypeError: unhashable type: 'list'
Sets can only contain hashable types. In the last line, we are checking for a list, so it threw a TypeError: unhashable type: ‘list’ because the list is an unhashable type.
Empty Set
If the input Set is empty and you try to check any element against it, it always returns False.
data = {}
print(21 in data)
# Output: False
None as an element
Since None is hashable, it qualifies to be an element in a set. What if we want to check None as an element? Well, if the Set contains None, the “in” operator returns True for the existence of None; otherwise, it returns False.
null_set = {19, None, "khushi"}
print(None in null_set)
# Output: True
Alternate approaches
The following are alternative approaches that you can use, but they are less reliable than the “in” operator.
- Using the “not in” operator
- Using operator.countOf() method
Approach 1: Using the not in operator
The not in operator is the negation of the in operator. So, not in operator returns False if the set contains an element. If the set does not contain an element, it returns True.
main_set = {19, 21, "Kaynes", -10, True}
print(48 not in main_set)
# Output: True
print("Kaynes" not in main_set)
# Output: False
Since, the Kaynes is included in the main_set, it returns False. 48 is not included in the main_set, so it returns True.
Approach 2: Using an operator.countOf()
The operator.countOf() method checks if specific elements are present in the set. If the element is present in the set, the .countOf() method returns True, otherwise False.
import operator as op
main_set = {19, 21, "Kaynes", -10, True}
print(op.countOf(main_set, 21) > 0)
# Output: True
print(op.countOf(main_set, 46) > 0)
# Output: False
That’s all!


