The Python issubset() function allows you to check if a set is a subset of another set.
a = {1, 2, 3}
b = {1, 2, 3, 4, 5, 6}
print(a.issubset(b))
#Output:
True
When working with different collections of data, the ability to easily determine properties of these objects can be useful.
One such property is if a set is a subset of another set.
A set X is a subset of another set Y if all of the elements of the set X are in the set Y.
In Python, you can use the issubset() function to check if a set is a subset of another set. issubset() returns a boolean value.
Below is a simple example showing you how to check if a set is a subset of another set using the issubset() function in Python.
a = {1, 2, 3}
b = {1, 2, 3, 4, 5, 6}
print(a.issubset(b))
#Output:
True
Using < and ≤ Operators to Check if Set is Subset in Python
In addition to the issubset() function, you can also use the < and ≤ operators to check if a set is a subset of another set.
The < operator checks if the subset is a proper subset, and ≤ checks if the set is contained in the other set with chance for equality.
Below are some examples showing how to use the < and ≤ operators to check if a set is a subset of another set in Python.
a = {1, 2, 3}
b = {1, 2, 3, 4, 5, 6}
print(a < a)
print(a < b)
print(a <= a)
print(a <= b)
#Output:
False
True
True
True
Using Python issuperset() Function to Check if Set is Superset of Another Set
If you want to go the other way and check if a set is a superset of another set, or that all of the elements of the set are also in the other set, then you can use the issuperset() function.
Just like issubset(), issuperset() returns a boolean value.
Below is a simple example showing you how to check if a set is a subset of another set using the issubset() function in Python.
a = {1, 2, 3}
b = {1, 2, 3, 4, 5, 6}
print(b.issuperset(a))
#Output:
True
Hopefully this article has been useful for you to learn how to use the issubset() function in Python.