# How to check if two given sets are disjoint in Python?

If the given two sets don’t have any element in common then it is said to be disjoint. The method isdisjoint() check whether the two sets are disjoint or not. If the sets are disjoint then the method returns **‘True’ **otherwise **‘False’**.

Example1: A = {0,2,4} B = {1,3,5} Example2: A = {1,2,3} B = {2,4,6}

Here, in Example1 both the sets have nothing common in them so both the sets are disjoint. Whereas in Example2 both the sets have a common element ‘2’. Therefore both the sets in Example2 are not disjoint.

#### Syntax:

set.isdisjoint(iterable)

**Parameters**: It takes iterable as an input for example list, tuple, dictionary, set, etc. The isdisjoint() method converts the iterable automatically into the set and then check whether the sets are disjoint or not. Remember that isdisjoint() only accepts a single argument.

**Return Value: **If both the sets are disjoint then it will return ‘True’, else ‘False’.

### Check whether the 2 Python sets are disjoint or not

Below is the given Python program to check if two Python sets are disjoint or not:

#Python program of disjoint sets. set1 = {1,2,3,4} set2 = {5,6,7,8} set3 = {'code', 'speedy', 'python'} set4 = {'python', 'program', 'disjoint'} #checking of disjoint of two sets print("set1 and set2 are disjoint:", set1.isdisjoint(set2)) print("set3 and set4 are disjoint:", set3.isdisjoint(set4))

#### Output:

set1 and set2 are disjoint: True set3 and set4 are disjoint: False

In the above example, set1 and set2 don’t have anything common. Therefore it returns ‘True’. But in set3 and set4 ‘python’ is in common. Therefore it returns ‘False’.

Example: check whether 2 sets are disjoint or not, with different iterable.

# python program of disjoint sets with different types of iterable. set1 = {1,2,3,4} list1 = [1,5,9] set2 = {'code', 'speedy', 'python'} list2 = ['program', 'disjoint', 'result'] #checking of disjoint of two sets print("set1 and list1 are disjoint:", set1.isdisjoint(list1)) print("set2 and list2 are disjoint:", set2.isdisjoint(list2))

#### Output:

set1 and list1 are disjoint: False set2 and list2 are disjoint: True

In the above example, set1 and set2 are set and list1 and list2 are list. In set1 and list1 have had an element in common i.e. ‘1’. Therefore it returns ‘False’. In set2 and list2 they don’t have anything in common. Therefore it returns ‘True.

## Leave a Reply

You must be logged in to post a comment.