Python .isdisjoint()
Published May 21, 2024
In Python, the .isdisjoint() method checks whether two sets have any common elements. If no common elements exist, it returns True; otherwise, it returns False.
Syntax
set1.isdisjoint(set2)
set1: Represents the set to be compared.set2: Represents the second set to be compared withset1to check for common elements.
Example
The below example shows the usage of the .isdisjoint() method:
# Creating three setsset1 = {1, 2, 3}set2 = {4, 5, 6}set3 = {3, 4, 5}# Checking if 'set1' and 'set2' are disjointprint(set1.isdisjoint(set2))# Checking if 'set1' and 'set3' are disjointprint(set1.isdisjoint(set3))
The above code produces the following output:
TrueFalse
In the above example, the .isdisjoint() method returns True for set1 and set2 since they have no elements in common and False for set1 and set3 since they share the element 3.
Codebyte Example
Below is a code byte example demonstrating the use of the .isdisjoint() method:
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours