How to Compare Sets Using the isdisjoint() Function in Python?

Estimated read time 1 min read

To compare sets using the isdisjoint() function in Python, you can use it to check if two sets have no common elements. The isdisjoint() function returns True if the sets have no intersection (i.e., no common elements), and False otherwise. Here’s an example:

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

if set2.isdisjoint(set1):
    print("set2 and set1 have no common elements")
else:
    print("set2 and set1 have at least one common element")

In this example, we have two sets, set1 and set2. We use the isdisjoint() function on set2 and pass set1 as the argument. The function checks if there are any common elements between the two sets. If there are no common elements, the code will print “set2 and set1 have no common elements”. Otherwise, it will print “set2 and set1 have at least one common element”.

The output of the above code will be:

set2 and set1 have no common elements

By using the isdisjoint() function, you can easily compare sets in Python to check if they have any common elements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply