Having a Set in a Sequence in Python
In Python, it is possible to check whether the elements of a set are included in a sequence - another set, a string, a list, a tuple. This can be done using the issubset
method. In its parameter, we specify the desired sequence. If the set is included in it, then the Boolean value True
is returned, otherwise - False
.
Let us have a set and a list:
st = {'a', 'b', 'c'}
lst = ['a', 'b', 'c']
Let's check if the elements of a set are in a list:
res = st.issubset(lst)
print(res) # True
Now let's compare the elements of the two sets:
st1 = {'1', '2', '3'}
st2 = {'1', '2', '4'}
res = st1.issubset(st2)
print(res) # False
The issubset
method also has a short form. It is used only when comparing two sets. Let's rewrite the previous example using it:
res = st1 <= st2
print(res) # False
Given a set and a string:
st = {'1', '2', '3', '4', '5', '6'}
txt = '123456'
Check that all elements of the set are present in the string.
Given a set and a tuple:
st = {'ab', 'cd', 'ef'}
tlp = ('ab', 'cd', 'ef')
Check that all elements of the set are in the tuple.
Two sets are given:
st1 = {1, 2, 3, 4, 5}
st2 = {1, 2, 3}
Check that all elements of the second set are in the first set.