Python issubset() Method

To check if set A is a subset of set B in Python, use the built-in issubset() method.

For example:

A = {1, 2, 3}
B = {1, 2, 3, 4, 5, 6}

print(A.issubset(B))

Output:

True

Alternatively, you can use comparison operators to do check if a set is a subset of another.

For example, to check if set A is a subset of B, use <= operator:

A = {1, 2, 3}
B = {1, 2, 3, 4, 5, 6}

print(A <= B)

Output:

True

If you came for a quick answer, I’m sure the above example is enough! However, if you are not familiar with subsets and supersets, I recommend reading the entire article. You will learn what it means to be a subset or superset in Python.

Subsets and Supersets: A Word about Set Theory

Given two sets A and B:

  • A is a subset of B if all the elements of set A are in set B.
  • A set is always a subset of itself.
  • A is a proper subset of B if the sets are not equal and set A is a subset of B.

Here is a Venn diagram illustration of set A being a subset of set B:

Python issubset() Method
Set A is a subset of B.

How to Check If a Set Is a Subset in Python

In Python’s built-in set data type, there is an issubset() method you can use to check if a set is a subset of another set.

The syntax is as follows:

set_A.issubset(set_B)

This returns True if set_A is a subset of set_B. Otherwise, it returns False.

Alternatively, you can also use comparison operators to do the same:

set_A <= set_B

For instance:

A = {1, 2, 3}
B = {1, 2, 3, 4, 5, 6}

print(A.issubset(B))
print(A <= B)

Output:

True
True

A Set Is a Subset of Itself

A set is always a subset of itself.

You can use the issubset() method to verify this:

A = {1, 2, 3}

print(A.issubset(A))

# Alternatively
print(A <= A)

Output:

True
True

How to Check If a Set Is a Proper Subset in Python

Set A is a proper subset of B if all elements of A are in B but B has at least one element that A does not.

In Python, there is no dedicated method to check if a set is a proper subset of another.

To check if a set is a proper subset of another one, use the greater than operator:

A = {1, 2, 3}
B = {1, 2, 3, 4, 5, 6}

# Proper subset
print(A < B)

Output:

True

Conclusion

Today you learned how to use issubset() method in Python. You also learned some basic set theory.

  • Set A is a subset of set B if set B has all the elements of set A.
  • Set A is a proper subset of B if all elements of A are in B but B has at least one element that A does not.
  • A set is always a subset of itself.

In Python, you can check if set A is a subset of set B by:

  • A.issubset(B)
  • A <= B

To check if a set A is a proper subset of set B:

  • A <= B

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading