Python

isdisjoint method in set

Click for All Topics

isdisjoint method in set - Python

  • This method is used to check whether two sets are disjoint or not.
  • Two sets are disjoint when there are no common elements between them.
  • This method returns true if both sets are disjoint otherwise it returns false.
  • isdisjoint method takes exactly one argument.
  • We can pass any iterable or collection as an argument e.g. list, tuple, set, dictionary, or string.
  • When we call this method with the set(main set) and pass one set(another set) as an argument then it iterates over the elements of the main set and check whether the element is present in another set, if any element is present in other set it returns true otherwise it returns false.

 

Syntax –

set_name.isdisjoint(iterable)

 

Parameter –

  • iterable → any iterable or collection e.g. list, tuple, dictionary, set, string.
  • Return value → bool(True or False).

 

Example –

				
					set1={1,3,5,7,9}
set2={2,4,6,8}

print("Set 1:",set1)
print("Set 2:",set2)

s=set1.isdisjoint(set2)
print("Answer:",s)

# Output -
# Set 1: {1, 3, 5, 7, 9}
# Set 2: {8, 2, 4, 6}
# Answer: True
				
			
  • In the above example, first we create two sets set1 with odd elements and set2 with some even elements.
  • After creating both the sets print both the sets on the output screen.
  • Then we called the .isdisjoint() method with set1 passed set2 as an argument and stored the result in the s variable.
  • Finally, print the variable s on the output screen.
  • In the above example, we see that the answer is True because there is no common element between both the sets.

 

The .isdisjoint() method with another iterable –

Example –

				
					my_set={"Hello","this","is","edSlash"}
string="Anurag Dubey"

print("My set:",my_set)
print("My string:",string)
print(my_set.isdisjoint(string))

# Output -
# My set: {'edSlash', 'is', 'Hello', 'this'}
# My string: Anurag Dubey
# True
				
			

Checking whether two sets are disjoint without using the inbuilt method –

Example –

				
					s1={1,2,3,4,5,6}
s2={2,4,6,8,10}
answer=True
for element in s1:
	if element in s2:
			answer=False
			break
print("Set 1:",s1)
print("Set 2:",s2)
print(answer)

# Output -
# Set 1: {1, 2, 3, 4, 5, 6}
# Set 2: {2, 4, 6, 8, 10}
# False