Python Set issubset()


Python Set issubset() method

Python Set issubset() method is used to check if the set is a subset of given set.

In this tutorial, you will learn the syntax and usage of Set issubset() method, with examples.

Syntax of Set issubset()

The syntax to call issubset() method is

set.issubset(s)

Parameters

Set issubset() method takes one parameter.

ParameterDescription
sRequired
Another set object.
Python Set issubset() method parameters table

Return value

Set issubset() method returns a boolean value of True if the set is a subset of given set s, otherwise returns False.

Usage

The following statement shows how to check if a set set_1 is a subset of another set set_2 using set.issubset() method.

set_1.issubset(set_2)

Examples

1. Checking if a set is subset of another set in Python

In this example, we shall take two sets in set_1 and set_2. We have to check if the set set_1 is a subset of the set set_2.

Call issubset() method on set_1 object, and pass set_2 object as argument. Since issubset() method returns a boolean value, we can use the method call as a condition in Python if else statement.

Python Program

# Take two sets
set_1 = {'a', 'c'}
set_2 = {'a', 'b', 'c', 'd'}

if set_1.issubset(set_2):
    print("set_1 is a SUBSET of set_2.")
else:
    print("set_1 is NOT a SUBSET of set_2.")

Output

set_1 is a SUBSET of set_2.

Since all the items of set_1 are present in set_2, set_1 is a valid subset of set_2.

set_1.issubset(set_2) returns True, and the if-block is executed.

Now, let us take the items in these two sets, such that set_1 is not a subset of set_2, and observe the output.

Python Program

# Take two sets
set_1 = {'a', 'm'}
set_2 = {'a', 'b', 'c', 'd'}

if set_1.issubset(set_2):
    print("set_1 is a SUBSET of set_2.")
else:
    print("set_1 is NOT a SUBSET of set_2.")

Output

set_1 is NOT a SUBSET of set_2.

Since all the items of set_1 are not present in set_2, set_1 is not a subset of set_2.

set_1.issubset(set_2) returns False, and the else-block is executed.

Summary

In this Python Set Tutorial, we learned how to use Set issubset() method to check if a set is a subset of another set in Python, with the help of well detailed examples.