The issubset()
method in sets checks whether a set is a subset of another set given as argument.
A set is a subset of another set if all of its elements are present in the second set. For example both sets, {1, 3, 5}
and {0, 2,
4}
are subsets of the set {0, 1, 2, 3, 4, 5}
since all of their elements are also present in this set.
Logically, every set is a subset of itself.
set1.issubset(set2)
set2 |
The set to check whether the current set is a subset of. |
The method returns True
, if set1
is a subset of set2
, else False
.
integers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
evens = {0, 2, 4, 6, 8}
odds = {1, 3, 5, 7, 9}
#check for subsets
print(integers.issubset(integers)) #it is a subset of itself
print(evens.issubset(integers)) #True
print(odds.issubset(integers)) #True
In the above case, the issubset()
method returns True
because all the sets are sub sets of integers
, including the integers
set itself.
integers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
evens = {0, 2, 4, 6, 8}
odds = {1, 3, 5, 7, 9}
#check for subsets
print(integers.issubset(evens)) #False
print(integers.issubset(odds)) #False
Using the <=
operator instead
The <=
is the operator version of the issubset()
function. Similarly, it returns True
if the first set is a subset of the second set, otherwise False
.
set1 <= set2
Returns True
if set1
is a subset of set2
, else False
.
integers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
evens = {0, 2, 4, 6, 8}
odds = {1, 3, 5, 7, 9}
#check for subsets
print(integers <= integers) #it is a subset of itself
print(evens <= integers) #True
print(odds <=integers)#True
print(evens <= odds) #False
print(odds <= evens) #False
Check for strict Subset
The <
operator is used to check whether a set is a strict subset of another set.
A subset is a strict subset when it is a subset of another set, but it does not contain all the elements of the larger set. In other words, the subset is smaller in size than the other set.
A set is not a strict subset of itself.
integers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
evens = {0, 2, 4, 6, 8}
odds = {1, 3, 5, 7, 9}
print(integers < integers) #it is a NOT its own subset
print(evens < integers) #True
print(odds < integers) #True