isdisjoint() function in Python


In this article, we will learn about how we can implement isdisjoint() function on set() data type. This function checks whether the sets passed as arguments have any element in common . In case any element is found, False is returned and True otherwise.

The isdisjoint() function can take lists, tuples & dictionaries as input arguments in addition to set inputs. THses types are implicitly converted to set type by the Python interpreter.

Syntax

<set 1>.isdisjoint(<set 2>)

Return value

Boolean True/False

Now let’s consider an illustration related to the implementation

Example

#declaration of the sample sets
set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = {'p','o','i','n','t'}
set_3 = {'p','y'}

#checking of disjoint of two sets
print("set1 and set2 are disjoint?", set_1.isdisjoint(set_2))
print("set2 and set3 are disjoint?", set_2.isdisjoint(set_3))
print("set1 and set3 are disjoint?", set_1.isdisjoint(set_3))

Output

set1 and set2 are disjoint? False
set2 and set3 are disjoint? False
set1 and set3 are disjoint? True

Explanation

Here as set_1 & set_2 have elements in common so bool value False is displayed. This is identical to the comparison between set_2 & set_3. But in the comparison between set_1 & set_3, bool value True is displayed as no common element is found.

Now let’s look at another illustration which involves iterable another than set type.

Note: The set_1 declared outside must be of the set type to make the interpreter aware about Comparision between sets. The argument present inside can be of any type which is implicitly converted to set type.

Example

#declaration of the sample iterables
set_1 = {'t','u','t','o','r','i','a','l'}
set_2 = ('p','o','i','n','t')
set_3 = {'p':'y'}
set_4 = ['t','u','t','o','r','i','a','l']

#checking of disjoint of two sets
print("set1 and set2 are disjoint?", set_1.isdisjoint(set_2))
print("set2 and set3 are disjoint?", set_1.isdisjoint(set_3))
print("set1 and set3 are disjoint?", set_1.isdisjoint(set_4))

Output

set1 and set2 are disjoint? False
set2 and set3 are disjoint? True
set1 and set3 are disjoint? False

Here also a check is made to find the common elements and the desired output is produced.

Conclusion

In this article, we learned how to use disjoint() function in Python and what all types of arguments are allowed to be compared by the help of this function.

raja
Published on 07-Aug-2019 07:45:43
Advertisements