Python Tutorial

Python Set isdisjoint() Method with Examples

TGTeam GyaniPanditNovember 16, 20263 min read

Hello friends! Sometimes the only thing you want to know about two groups is: do they have anything in common at all? For that, Python gives us isdisjoint(). The isdisjoint() method checks whether two sets have no items in common. Sets with nothing in common are called disjoint. The method returns True if there is no common item and False if there is at least one. Let’s see how it works.

a.isdisjoint(b)

Basic Example

x = {1, 2, 3}
y = {4, 5}
z = {3, 6}
print(x.isdisjoint(y))
print(x.isdisjoint(z))

Output:

True
False

x and y share nothing, so they are disjoint. x and z share the number 3, so they are not.

With Lists and Other Iterables

print(x.isdisjoint([7, 8]))

Output:

True

Unlike most set operators, there is no operator form of isdisjoint(); you always call the method, and it accepts any iterable.

Here is a small puzzle: what happens with two empty sets?

Two Empty Sets

print(set().isdisjoint(set()))

Output:

True

Empty sets have nothing in common, so they are disjoint, even with each other.

You might be thinking, why not just find the intersection and check if it is empty? You can, but there is a better way.

isdisjoint() vs Checking the Intersection

print(len(x & y) == 0)

Output:

True

This gives the same answer, but it builds a whole new set first. isdisjoint() stops as soon as it finds one common item, so it is cleaner and usually faster, especially for large sets. See also intersection().

Now let’s use isdisjoint() in a few practical examples.

Practical Examples

1. Do Two Batches Share Any Student?

morning = {"Riya", "Aman"}
evening = {"Neha", "Kabir"}
print(morning.isdisjoint(evening))

Output:

True

2. Time-Slot Clash Check

booked = {9, 10, 11}
request = {12, 13}
print("Free" if booked.isdisjoint(request) else "Clash")
request = {11, 12}
print("Free" if booked.isdisjoint(request) else "Clash")

Output:

Free
Clash

3. Blocking Reserved Usernames

banned = {"admin", "root"}
for name in ["riya", "admin"]:
    print(name, "ok" if banned.isdisjoint({name}) else "not allowed")

Output:

riya ok
admin not allowed

Practice Question

What does print({2, 4}.isdisjoint({1, 3, 5})) print?

Answer: True. The even numbers and the odd numbers have nothing in common.

So friends, remember: two sets are disjoint when they have no items in common. There is no operator for isdisjoint(); you can check not (a & b) instead, but that is less efficient. And like most set methods, it accepts any iterable, such as a list, tuple or string. Whenever your question is simply “do these share anything?”, reach for isdisjoint().

More set methods: Set methods in Python · issubset() · intersection() · difference()

Turn reading into skillsCertificate courses in AI, Data Science and programming.
Explore Courses