The issubset() method checks whether every element of one set is present in another set. It returns True when the set is a subset of the other set and False otherwise.
Example: In this example, issubset() checks whether all elements of s2 are present in s1.
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5}
print(s2.issubset(s1))
Output
True
Explanation:
- s2.issubset(s1) checks whether every element of s2 exists in s1.
- Since 4 and 5 are both present in s1, the result is True.
Syntax
set_obj.issubset(other_set)
- Parameters: other_set - The set or iterable against which the set is compared.
- Return Value: Returns True if all elements are present in other_set; otherwise, returns False.
Example
Example 1: In this example, both sets are compared in different directions to show that subset comparison is not symmetric.
a = {1, 3, 5}
b = {1, 2, 3, 4, 5}
print(a.issubset(b))
print(b.issubset(a))
Output
True False
Explanation:
- a.issubset(b) returns True because all elements of a are present in b.
- b.issubset(a) returns False because b contains elements that are not in a.
Example 2: An empty set is a subset of every set because it contains no elements that need to be missing from the other set.
a = set()
b = {10, 20, 30}
print(a.issubset(b))
Output
True
Explanation:
- a is empty, so it has no elements that could violate the subset condition.
- Therefore, a.issubset(b) returns True.
Example 3: In this example, three sets are used to check different subset relationships.
a = {1, 2}
b = {1, 2, 3, 4}
c = {2, 4}
print(a.issubset(b))
print(c.issubset(b))
print(b.issubset(a))
Output
True True False
Explanation:
- a.issubset(b) returns True because 1 and 2 are in b.
- c.issubset(b) returns True because 2 and 4 are in b.
- b.issubset(a) returns False because b contains 3 and 4, which are not in a.