Python Set isdisjoint()

The isdisjoint() method returns True if two sets don't have any common items between them, i.e. they are disjoint. Else the returns False.

Example

A = {1, 2, 3, }
B = {4, 5, 6}

# checks if set A and set B are disjoint print(A.isdisjoint(B))
# Output: True

isdisjoint() Syntax

The syntax of the isdisjoint() method is:

A.isdisjoint(B)

Here, A and B are two sets.


isdisjoint() Parameter

The isdisjoint() method takes a single argument:

  • B - a set that performs disjoint operation with set A

We can also pass iterables like list, tuple, dictionary or string. In that case, isdisjoint() first converts the iterables to sets and then checks if they are disjoint.


isdisjoint() Return Value

The isdisjoint() method returns:

  • True if set A and set B are disjoint
  • False if set A and set B are not disjoint

Example 1: Python Set disjoint()

A = {1, 2, 3}
B = {4, 5, 6}
C = {6, 7, 8}

print('A and B are disjoint:', A.isdisjoint(B)) print('B and C are disjoint:', B.isdisjoint(C))

Output

A and B are disjoint: True
B and C are disjoint: False

In the above example, we have used isdisjoint() to check if set A, B and C are disjoint with each other.

The set A and B are disjoint to each other as they do not have any common item. Hence, it returned True. The set B and C have a common item, 6. So the method returns False.


Example 2: isdisjoint() with Other Iterables as Arguments

# create a set A
A = {'a', 'e', 'i', 'o', 'u'}

# create a list B
B = ['d', 'e', 'f']

# create two dictionaries C and D 
C = {1 : 'a', 2 : 'b'}
D = {'a' : 1, 'b' : 2}

# isdisjoint() with set and list
print('A and B are disjoint:', A.isdisjoint(B))

# isdisjoint() with set and dictionaries
print('A and C are disjoint:', A.isdisjoint(C))
print('A and D are disjoint:', A.isdisjoint(D))

Output

A and B are disjoint: False
A and C are disjoint: True
A and D are disjoint: False

In the above example, we have passed list and dictionaries as the arguments to the method isdisjoint(). The set A and list B have a common item 'a', so they are not disjoint sets.

The item 'a' from the set A and key 'a' of the dictionary D is common. So they are not disjoint sets.

However, A and dictionary D are disjoint because the values of dictionaries are not compared with the set items.

Did you find this article helpful?