Set isdisjoint() Method in Python

Python Set isdisjoint() Method

The isdisjoint() method is used to check if two sets have no elements in common. It returns True if the sets are disjoint (i.e., they have no common elements), and False if they have at least one common element.

Syntax of the isdisjoint() method:

result = set1.isdisjoint(set2)

Parameters:

  • set1: The first set you want to check for disjointness.
  • set2: The second set you want to check for disjointness.

Example:

# Creating two sets
set1 = {1, 2, 3, 4, 5}
set2 = {6, 7, 8, 9}

# Checking if set1 and set2 are disjoint
result = set1.isdisjoint(set2)

print(result)  # Output: True (set1 and set2 have no common elements)

In this example, the isdisjoint() method is applied to set1 and set2. Since there are no common elements between the two sets, the result is True, indicating that they are disjoint.

Let's see another example where the sets have at least one common element:

# Creating two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Checking if set1 and set2 are disjoint
result = set1.isdisjoint(set2)

print(result)  # Output: False (set1 and set2 have common elements, 4 and 5)

In this case, the isdisjoint() method returns False because there are common elements (4 and 5) between set1 and set2.