A set is disjoint to another set if there are no elements in common between the two sets. This means that the intersection of the two sets is an empty set.
For example, set {1, 3, 5}
and {2, 4, 6}
are disjoint because they don't have any common element(s).
The isdisjoint()
method checks if the current set is disjoint with another set given as argument.
set_a.isdisjoint(set_b)
set_b |
This can be a set or any other iterable object. |
The method returns True
if set_a
has no common elements with set_b
, else False
.
set1 = {1, 3, 5, 7, 9}
set2 = {0, 2, 4, 6, 8}
#check if whether the two sets are disjoint
print(set1.isdisjoint(set2)) #True
print(set2.isdisjoint(set1)) #True
In the above case, the isdisjoint()
method method returns True
the two sets have no common elements.
set1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} #digits
set2 = {1, 3, 5, 7, 9}#odds
set3 = {0, 2, 4, 6, 8}#evens
#check for disjoints
print(set1.isdisjoint(set2)) #False
print(set1.isdisjoint(set3)) #False
Using other iterables
As earlier mentioned, the iterable given as argument does not necessarily have to be a set. It can be any iterable object.
Using a list as the argument
integers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} #digits
odds = [1, 3, 5, 7, 9] # a list
evens = [0, 2, 4, 6, 8] # a list
#check for disjoints
print(integers.isdisjoint(odds)) #False
print(integers.isdisjoint(evens)) #False
print(integers.isdisjoint([-1, -2, -3, -4, -5])) #True