Having an Element in a Set in Python
To check if an element is in a set, use the in
operator. The desired element is specified to the left of the operator, and the set in which to look for it is specified to the right. If the element is in the set, the Boolean value True
is returned, otherwise False
.
Let us have a set:
st = {'a', 'b', 'c'}
Let's check if it contains the element 'a'
:
res = 'a' in st
print(res) # True
Now let's try to find the element 'e'
in the set:
res = 'e' in st
print(res) # False
You can also check for the presence of an element in several sets at once. To do this, you should also use the union operator &
:
st1 = {1, 2, 3, 4}
st2 = {3, 4, 5, 6}
print(3 in st1 & st2) # True
To go the other way and find out if an element is in a set, you can use the construction not in
:
st = {'1', '2', '3'}
res = '4' not in st
print(res) # True
Given a set:
st = {1, 2, 3, 4, 5}
Given a variable:
num = 3
Check that the value of this variable is contained in the set.
The following code is given:
st1 = {'1', '2', '3'}
st2 = {'4', '5', 3}
print('3' in st1 & st2)
Tell me what will be output to the console.
The following code is given:
st = {'ab', 'bc', 'cd'}
txt = 'bc'
print(txt not in st)
Tell me what will be output to the console.
The following code is given:
st = {'x', 'y', 'z', 'w'}
txt = 'yz'
print(txt not in st)
Tell me what will be output to the console.