Python Set isdisjoint:
The isdisjoint() method returns true if there are no common elements in both sets. Otherwise, this method returns False. In other words, Set A and Set B are referred to as a disjoint set, if the intersection of this set is an empty set.
Method signature
The signature for the isdisjoint() method is as shown below. Here, A and B are set. In this case, the method returns True if there are no common elements in A and B. Otherwise, it returns False.
A.isdisjoint(B)
Method parameters and return type
- The isdisjoint() method takes one parameter
- However, it returns the boolean value True or False depending on the data set.
Python Set isdisjoint Examples:
Example 1:
In this example, let us take a set A and a set B with a set of numbers.
#Initializing the Set
A = {35,45,55}
B={19,29,39}
C={15,25,35}
# Checking if A and B are disjoint sets
result=A.isdisjoint(B)
print("If A and B are disjoint sets",result)
# Checking if A and C are disjoint sets
result=A.isdisjoint(C)
print("If A and C are disjoint sets",result)
Output
If A and B are disjoint sets True
If A and C are disjoint sets False
Example 2:
In this example, let us consider a set containing Colors. As we already know, Python is case sensitive. So, if the color name doesn’t match exactly, this method will return True. As we see in this example, Set C has the color “blue” which is different from the color “Blue” in Set A. As a result, it considers A and C as disjoint set.
#Initializing the Set
A={"Orange", "Blue", "Cyan", "Red"}
B={"Orange", "cyan"}
C={"blue"}
# Checking if A and B are disjoint
print("If A and B are disjoint sets ",B.isdisjoint(A))
# Checking if A and C are disjoint
print("If A and C are disjoint sets ",C.isdisjoint(A))
Output
If A and B are disjoint sets False
If A and C are disjoint sets True
Example 3:
In this example, let us demonstrate the isdisjoint method on a mixed set.
#Initializing the Set
A={"Ram", 15.5,"Sam", 25, "Harry",3,"John",8}
B={"Sam",25}
C={30,15.5,"john"}
# Checking if A and B are disjoint
print("If A and B are disjoint sets ",B.isdisjoint(A))
# Checking if A and C are disjoint
print("If A and C are disjoint sets ",C.isdisjoint(A))
Output
f A and B are disjoint sets False
If A and C are disjoint sets False
Conclusion
The isdisjoint() method returns a boolean value to indicate if both the sets contain unique, non-repeating elements.
References
Happy Learning 🙂