Have you ever wondered how programmers find out if an element in one set exists in another set or not? They find this information through the issubset() and issuperset Python methods.
Let us say P and Q are two sets. In the diagram, you can see that set P has all the elements of set Q. Therefore, we say P is the superset of Q, and Q is the subset of P.
Return Value from issuperset()
The issuperset() Python method works on boolean operations and follows the syntax:
P. issuperset(Q)
The above code checks if P is the superset of Q. If yes, it returns True and False if it is not a superset of Q.
Example of how issuperset() works
Let us understand the issuperset() method with an example:
# creating sets
A = {12, 14, 18, 22, 24}
B = {12, 14, 18}
C = {22, 24}
print (A. issuperset(B)) # returns True
print (C. issuperset(A)) # returns False
print (A. issuperset(C)) # returns True
Output:
True
False
True
Questions and Answers
Q1. What is issuperset in Python?
The issuperset() is a method in Python that helps you find out if a set is a superset of another set. A superset is usually a set that contains one or more subsets.
# creating sets
A = {12, 14, 18, 22, 24}
B = {12, 14, 18}
C = {22, 24}
print (A. issuperset(B)) # returns True
print (C. issuperset(A)) # returns False
print (A. issuperset(C)) # returns True
In the above example, A is a superset of B and C. We can also say that B and C are subsets of A.
Q2. How do you find subsets in Python?
Like the issuperset() method, Python also has an issubset() method to find subsets.
# creating sets
A = {12, 14, 18, 22, 24}
B = {12, 14, 18}
C = {22, 24}
print (A. issubset(B))
print (C. issubset(A))
print (B. issubset(A))
Output:
False
True
True
The program lets us know that B and C are subsets of A.
Q3. How do I find my superset?
You can find a superset by using issuperset() in Python. It follows the syntax:
X. issuperset(Y)
Where X and Y are the two sets, you want to check.
Example:
# creating sets
A = {'h', ',o', 'l', 'a', 'n', 'i', 'n', 'a'}
B = {'h', ',o', 'l', 'a'}
C = {'n', 'i', 'n', 'a'}
print (A. issuperset(B))
print (A. issuperset(C))
print (B. issuperset(A))
Output:
True
True
False
Q4. What is issubset in Python?
Similar to the issuperset() in Python, issubset() is a method that helps you compare two relations between two sets. The method returns True if the set is a subset of the argument, and returns False if it is not a subset.
Example:
# creating sets
A = {'h', ',o', 'l', 'a', 'n', 'i', 'n', 'a'}
B = {'h', ',o', 'l', 'a'}
C = {'n', 'i', 'n', 'a'}
print (A. issubset(B))
print (C. issubset(A))
print (B. issubset(A))
Output:
False
True
True
Leave a Reply