Python Set isdisjoint()

Python Set isdisjoint() method

Python Set isdisjoint() method is used to check if the two sets are disjoint, i.e., if they have an intersection or not.

Disjoint sets do not have any items in common and therefore no intersection between the elements.

In this tutorial, you will learn the syntax and usage of Set isdisjoint() method, with examples.

Syntax of Set isdisjoint()

The syntax to call isdisjoint() method is

set.isdisjoint(s)

Parameters

Set issubset() method takes one parameter.

ParameterDescription
sRequired
Another set object.
Python Set issubset() method parameters table

Return value

Set isdisjoint() method returns a boolean value of True if the set has no intersection with the given set s, otherwise returns False.

Usage

The following statement shows how to check if a set set_1 and set_2 are disjoint sets using set.isdisjoint() method.

set_1.isdisjoint(set_2)

Examples

1. Checking if two sets are disjoint in Python

In this example, we shall take two sets in set_1 and set_2. We have to check if these two sets are disjoint.

Call isdisjoint() method on set_1 object, and pass set_2 object as argument. Since isdisjoint() method returns a boolean value, we can use the method call as a condition in Python if else statement.

Python Program

# Take two sets
set_1 = {'a', 'b', 'c', 'd'}
set_2 = {'k', 'm'}

if set_1.isdisjoint(set_2):
    print("set_1 and set_2 are DISJOINT.")
else:
    print("set_1 and set_2 are NOT DISJOINT.")
Run Code Copy

Output

set_1 and set_2 are DISJOINT.

Since there are no common items between set_1 and set_2, no intersection, and therefore disjoint sets.

set_1.isdisjoint(set_2) returns True, and the if-block is executed.

Now, let us take the items in these two sets, such that set_1 and set_2 are not disjoint, and observe the output.

Python Program

# Take two sets
set_1 = {'a', 'm', 'd'}
set_2 = {'a', 'b', 'c', 'd'}

if set_1.isdisjoint(set_2):
    print("set_1 and set_2 are DISJOINT.")
else:
    print("set_1 and set_2 are NOT DISJOINT.")
Run Code Copy

Output

set_1 and set_2 are NOT DISJOINT.

Since there are some (two) common items between set_1 and set_2, these are not disjoint sets.

set_1.isdisjoint(set_2) returns False, and the else-block is executed.

Summary

In this Python Set Tutorial, we learned how to use Set isdisjoint() method to check if two given sets are disjoint in Python, with the help of well detailed examples.

Related Tutorials

Code copied to clipboard successfully 👍