Python Set issubset: The Complete Guide

Python Set issubset() method returns True if all items of a set are present in another set (passed as an argument). If not, then it returns False. Lets, assume A={1,2,4} and B={1,2,3,4,5} are two sets. So we can see the following figure.

Python Set issubset()

Python Set issubset()

Python Set issubset() is a built-in function that is used to find whether a set is a subset of another set or not. If all the elements of one set are present in another set, then the first set is called a subset of the second set. This means the second set must contain values that are present in the first set.

Set A is said to be the subset of Set B if all items of A are in B. Here, Set A is a subset of B.

Syntax

First_Set.issubset(Second_Set)

Here, this syntax will check if First_Set is a subset of Second_Set or not.

Return Value

The function returns two types of values-

True: If First_Set is a subset of Second_Set

False: If First_Set is not a subset of Second_Set

Example

See the following code.

# app.py

# Declaring two sets
# Even nums between 2 and 10
set1 = {2, 4, 6, 8, 10}
# Multiple of 4 from 4 to 10
set2 = {4, 8}
# Multiple of 4 from 4 to 20
set3 = {4, 8, 12, 16, 20}

# priting both the sets
print("Set1 is: ", set1)
print("Set2 is : ", set2)
print("Set3 is: ", set3)
# Now we will find if they are disjoint
print("Is Set2 Subset of Set1? ", set2.issubset(set1))
print("Is Set3 Subset of Set1? ", set3.issubset(set1))

Output

Set1 is:  {2, 4, 6, 8, 10}
Set2 is :  {8, 4}
Set3 is:  {4, 8, 12, 16, 20}
Is Set2 Subset of Set1?  True
Is Set3 Subset of Set1?  False

In this program, we have declared three sets, Set1, which is even numbers from 1 to 10, Set2, which contains a multiple of 4 from 4 to 10, and Set3, which includes a multiple of 4 from 4 to 20.

Now, we are finding if Set2 is a subset of Set1 or not. So, we can see that all the elements of Set2 are present in Set1. So, Set2 is a subset of Set1.

On the other hand, we can see that not all the elements are present in Set1 of Set3, so it is not a subset of Set1. That’s why the return value is False.

See the following second example.

# app.py

A = {11, 21, 19}
B = {11, 21, 19, 46, 18}
C = {11, 21, 46, 18}

# Returns True
print(A.issubset(B))

# Returns False
# B is not subset of A
print(B.issubset(A))

# Returns False
print(A.issubset(C))

# Returns True
print(C.issubset(B))

Output

python3 app.py
True
False
False
True

That’s it for this tutorial.

See also

Python set isdisjoint()

Python set intersection_update()

Python set intersection()

Python set discard()

Python set difference_update()

Python set difference()

Python set copy()

Python set clear()

Python set add()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.