Python Set issubset() Method

Python Set issubset() method returns True if all the elements of set A are present in set B; otherwise, it returns False.

Visual Representation

Visual Representation of Python Set issubset() MethodSyntax

First_Set.issubset(Second_Set)

Parameters

Second_Set(required): Any other set to compare with.

If no argument is passed, it raises a TypeError.

Return Value

It returns boolean value:

  1. True: If First_Set is a subset of Second_Set.
  2. False: If First_Set is not a subset of Second_Set.

Example 1: How does the issubset() method work?

#Multiples of 2 from 2 to 10
set1 = {2, 4, 6, 8, 10} 

# Multiple of 4 from 4 to 10 
set2 = {4, 8} 

print("Is Set2 Subset of Set1? ", set2.issubset(set1))
print("Is Set1 Subset of Set2? ", set1.issubset(set2))

Output

Is Set2 Subset of Set1? True
Is Set1 Subset of Set2? False

Example 2: Working with three-set

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


print(A.issubset(B))

print(B.issubset(A))

print(A.issubset(C))

print(C.issubset(B))

Output

True
False
False
True

Using subset (<=) operator

You can also use the subset operator (<=) to check if one set is a subset of another.

set1 = {2, 4, 6, 8, 10} 

set2 = {4, 8} 

print("Is Set2 Subset of Set1? ", set2 <= set1)
print("Is Set1 Subset of Set2? ", set1 <= set2)

Output

Is Set2 Subset of Set1? True
Is Set1 Subset of Set2? False

Leave a Comment

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