Python Set isdisjoint()

Python Set x.isdisjoint(y) method checks if the two sets x and y are disjoint or not. The method returns true if the two sets are disjoint or false otherwise.

In this tutorial, we will learn the syntax of set.isdisjoint() method and go through examples covering different scenarios for the arguments that we pass to isdisjoint() method.

Syntax

The syntax of set.isdisjoint() method is

</>
Copy
set.isdisjoint(other)

where

ParameterDescription
otherA set.

Examples

1. Check if sets x, y are disjoint

In the following program, we will take two sets: x, y; such that they have no elements in common. Meaning x and y are disjoint. x.isdisjoint(y) must return True.

Python Program

</>
Copy
x = {'apple', 'banana', 'cherry'}
y = {'mango', 'guava'}

if x.isdisjoint(y) :
    print('x and y are disjoint sets.')
else :
    print('x and y are not disjoint sets.')

Program Output

x and y are disjoint sets.

2. Check if sets x, y are disjoint (x, y have common elements)

In the following program, we will take two sets: x, y; such that they have some elements in common. Meaning x and y are not disjoint. x.isdisjoint(y) must return False.

Python Program

</>
Copy
x = {'apple', 'banana', 'cherry'}
y = {'apple', 'guava'}

if x.isdisjoint(y) :
    print('x and y are disjoint sets.')
else :
    print('x and y are not disjoint sets.')

Program Output

x and y are not disjoint sets.

Conclusion

In this Python Tutorial, we learned about Python set method isdisjoint(). We have gone through the syntax of isdisjoint() method, and its usage with example programs.