Python Set isdisjoint() method returns True if no elements are common to both sets; otherwise, it returns False.
For example, if A={1,2,3} and B={5,7,9} are two sets, we can see that there is no common element in them, so they are known as disjoint.
Visual Representation
Syntax
set1.isdisjoint(set2)
Parameters
set2(required): It is the set in which you are comparing the set1.
Return Value
It returns a boolean value: True if those sets are disjoint and False if given sets are not.
Example 1: How to Use isdisjoint() Method
# even numbers
set1 = {2, 4, 6, 8, 10}
# Multiple of 3 between 1 to 10
set2 = {3, 6, 9}
# odd numbers
set3 = {1, 3, 5, 7}
# priting both the sets
print("Set1 is: ", set1)
print("Set2 is : ", set2)
print("Set3 is: ", set3)
# Now we will find if they are disjoint
print("Are Set1 and Set2 disjoint? ", set1.isdisjoint(set2))
print("Are Set1 and Set3 disjoint? ", set1.isdisjoint(set3))
Output
Set1 is: {2, 4, 6, 8, 10}
Set2 is : {9, 3, 6}
Set3 is: {1, 3, 5, 7}
Are Set1 and Set2 disjoint? False
Are Set1 and Set3 disjoint? True
Example 2: Using another iterables as arguments
When passing other iterables, such as List, tuple, and dictionary,, to the isdisjoint() method in Python, it checks for disjointness by considering these iterables as sets. For instance, when a dictionary is passed, only its keys are considered for determining if the sets are disjoint.
# Set A
A = {11, 21}
# List lis
lis = [11, 21, 46]
# Tuple t
t = (10, "Ankit")
# Dictionary dict, Set is formed on Keys
dict = {11: 'Eleven', 19: 'KK'}
# Dictionary dict2
dict2 = {'Four': 4, 'Five': 5}
print("Set A and List lis disjoint?", A.isdisjoint(lis))
print("Set A and tuple t are disjoint?", A.isdisjoint(t))
print("Set A and dict are disjoint?", A.isdisjoint(dict))
print("Set A and dict2 are disjoint?", A.isdisjoint(dict2))
Output
Set A and List lis disjoint? False
Set A and tuple t are disjoint? True
Set A and dict are disjoint? False
Set A and dict2 are disjoint? True
Example 3: What happens if both sets are empty
set1 = set()
set2 = set()
# priting both the sets
print("Set1 is: ", set1)
print("Set2 is : ", set2)
print("Are Set1 and Set2 disjoint? ", set1.isdisjoint(set2))
Output
Set1 is: set()
Set2 is : set()
Are Set1 and Set2 disjoint? True