Venn diagram of disjoint sets

Python – Check if two sets are disjoint sets

In this tutorial, we will look at how to check whether two sets are disjoint sets or not in Python with the help of examples.

Two sets are said to be disjoint sets if they do not have any common elements between them. That is, the intersection of the sets is an empty set. Let’s look at an example.

Venn diagram of disjoint sets

You can see that sets A and B in the above example do not have any shared elements between them and thus are disjoint sets.

Python comes with a built-in set data structure to implement a set. It also has a number of additional functions to help you with common operations on sets such as union, intersection, difference, etc.

To check if two sets are disjoint sets or not in Python, you can use the set isdisjoint() function. The following is the syntax:

# check if sets a and b are disjoint sets
a.isdisjoint(b)

It returns True if the sets are disjoint and False otherwise. Let’s look at an example.

# create two sets
a = {1,2,3}
b = {4,5}
# check if the sets are disjoint
a.isdisjoint(b)

Output:

True

We get True as the output since there are no common elements between the sets. Let’s look at another example.

📚 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.

# create two sets
a = {1,2,3}
b = {2,4,5}
# check if the sets are disjoint
a.isdisjoint(b)

Output:

False

We False as the output since element 2 is shared between both sets.

You might also be interested in –

Author

  • Piyush Raj

    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.

Scroll to Top