Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Set isdisjoint() method



The Python Set isdisjoint() method is used to check if two sets have no elements in common. It returns True if the sets are disjoint which means their intersection is empty otherwise it returns False.

This method can be used with any iterable not just only with sets. If any element in the other set or iterable is found in the original set then isdisjoint() method returns False. Otherwise it returns True.

Syntax

Following is the syntax and parameters of Python Set isdisjoint() method −

set1.isdisjoint(other)

Parameter

This method accepts another set object as a parameter to compare it with the current set to determine whether both are disjoint.

Return value

This method returns boolean values as True or False.

Example 1

Following is the basic example which shows the usage of isdisjoint() method with two sets which have no elements in common −

# Define two sets
set1 = {1, 2, 3}
set2 = {4, 5, 6}

# Check if the sets are disjoint
print(set1.isdisjoint(set2))  

Output

True

Example 2

In this example we show how the isdisjoint() method works with two sets that have common elements −

# Define two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Check if the sets are disjoint
print(set1.isdisjoint(set2))  

Output

False

Example 3

The disjoint() method can be used with a set or with other data types such as list, tuple etc. Here in this example we applied the disjoint() method on a set and a list −

# Define a set and a list
my_set = {1, 2, 3}
my_list = [4, 5, 6]

# Check if the set and the list are disjoint
print(my_set.isdisjoint(my_list))  

Output

True

Example 4

This example shows how isdisjoint() method can be used in a conditional statement, to perform an action based on whether the sets are disjoint or not −


# Define two sets
set1 = {1, 2, 3}
set2 = {4, 5, 6}

# Perform an action based on whether the sets are disjoint
if set1.isdisjoint(set2):
    print("The sets have no common elements.")
else:
    print("The sets have common elements.")

Output

The sets have no common elements.
python_set_methods.htm
Advertisements