To check if a set contains a specific element in Python, you can use the Python in operator.
set_of_numbers = {0,1,2,3,4}
if 3 in set_of_numbers:
print("3 is in the set of numbers!")
else:
print("3 is not in the set of numbers!")
#Output:
3 is in the set of numbers
If you want to check if an element is not in a set, you can use the Python not in operator.
set_of_numbers = {0,1,2,3,4}
if 5 not in set_of_numbers:
print("5 is not in the set of numbers!")
else:
print("5 is in the set of numbers!")
#Output:
5 is not in the set of numbers
In Python, sets are unordered collections of items. When working with sets, it can be useful to know if certain elements are contained in a set.
We can easily check if a set contains an element in Python.
To check if a set contains an element, we can use the Python in operator. The in operator checks if an element is in a set and returns a boolean value.
Below is a simple example of how to use the in operator in Python to check if an element is in a set.
set_of_numbers = {0,1,2,3,4}
print(3 in set_of_numbers)
print(5 in set_of_numbers)
#Output:
True
False
How to Check if a Set Contains an Element with not in in Python
We can also go the other way and check if a set doesn’t contain an element. To check if a set doesn’t contain an element in Python, we use the Python not in operator.
Below are a few examples of how to use not in to check if a set doesn’t contain a particular element in Python.
set_of_numbers = {0,1,2,3,4}
print(3 not in set_of_numbers)
print(5 not in set_of_numbers)
#Output:
False
True
Hopefully this article has been useful for you to learn how to check if a set contains an element in Python.