Venn diagram showing set b as superset of set a

Python – Check if Set is a Superset

In this tutorial, we will look at how to check whether a set in Python is a superset of another set with the help of some examples.

Let’s say we have two sets, A and B. Now, if all the elements of set A are present in set B then A is said to be a subset of B, and B is called the superset of A. Here’s an example –

Venn diagram showing set b as superset of set a

You can see that set B contains all the elements of set A and thus B is a superset of A and A is a subset of B.

The Python set data structure comes with a number of built-in functions to accomplish common set operations like union, intersection, difference, etc. You can use the Python set issuperset() function to check whether a set is a superset of another set. The following is the syntax:

# check if a is a superset of b
a.issuperset(b)

We call the issuperset() function from set a and pass the set b as an argument to check whether set a is a superset of set b. It returns a boolean value. Let’s look at an example.

# create two sets
a = {1, 2, 3, 4}
b = {1, 2, 3}
# check if a is superset of b
a.issuperset(b)

Output:

True

We get True as the output since a contains all the elements from set b and hence is a superset of set b. Let’s look at another example.

# create two sets
a = {1, 2}
b = {1, 2, 3}
# check if a is superset of b
a.issuperset(b)

Output:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

False

Here we get False as the output since a does not contain all the elements from set b and hence it’s not a superset of set b.

Alternatively, you can use the >= operator to check if a set is a superset of another set. For example,

# create two sets
a = {1, 2, 3, 4}
b = {1, 2, 3}
# check if a is superset of b
a >= b

Output:

True

We get the same result as we did with the set issuperset() function.

You might also be interested in –

Author

  • Piyush Raj profile picture

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts
Scroll to Top