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.
What are disjoint sets?
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.
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.
Check for Disjoint Sets in Python
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.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 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 –