FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Set isdisjoint() method with examples




Python Set isdisjoint() method checks whether the two sets are disjoint sets or not. If the sets are disjoint, this method returns true else it returns false. Two sets are said to be disjoint if they do not have any common elements. For example Set {1, 2, 3} and Set {4, 5, 6} are disjoint sets because they do not have any common elements.

Set isdisjoint() method Syntax

set.isdisjoint(iterable)

Parameter: It accepts any iterable such as Set, List, tuple, dictionary etc. as a parameter and converts it into a Set and then checks whether the Sets are disjoint or not.
Return Value: It returns a boolean value true or false. True if the sets are disjoint else it returns false.

Python Set isdisjoint() method Example

In the following example, we have three Sets X, Y and Z and we are checking whether set X & Y and X & Z are disjoint sets or not using isdisjoint() method. Since Set X and Y have common elements the isdisjoint() method returns false and because X and Z have no common elements, this method returns true for them.

# Set X
X = {4, 5}

# Set Y
Y = {4, 5, 6}

# Set Z
Z = {10, 20, 30}

print("X and Y are disjoint Sets?", X.isdisjoint(Y))
print("X and Z are disjoint Sets?", X.isdisjoint(Z))

Set isdisjoint() method with other iterable such as List, Tuple & Dictionary

When we pass the other iterable such as List, tuple and dictionary in isdisjoint() method, it converts them into a Set and then checks whether the sets are disjoint or not.
When converting a dictionary to a Set, the keys are considered as the elements of the converted set.

# Set A
A = {4, 5}

# List lis
lis = [10, 20, 30]

# Tuple t
t = (10, "hello")

# Dictionary dict, Set is formed on Keys
dict = {4 : 'Four', 5: 'Five'}

# 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))






Leave Comment