Set method

set.isdisjoint()

Returns True when this set and the other collection have no element in common, and False as soon as one is shared.

IntermediateEvery example below runs in your browser. Change the code and press Run.

set.isdisjoint(other)

a.isdisjoint(b) answers "do these two have nothing in common?". Two sets with no shared element are called disjoint.

You could write not (a & b), but isdisjoint() says what you mean and can stop at the first shared element instead of building a whole new set.

Use it for clash checks: a booking against taken time slots, a list of ingredients against allergies, chosen usernames against banned words.

Parameters

ParameterWhat it is
other
required
A set or other iterable to compare with.

Return value

True if there are no shared elements, otherwise False.

Examples

1Basic check

Pythoneditable
a = {1, 2, 3}
print(a.isdisjoint({4, 5}))
print(a.isdisjoint({3, 4}))
Output
True
False

2Allergy check

Pythoneditable
allergies = {"peanuts", "shellfish"}
dishes = {
    "pad thai": ["noodles", "peanuts", "egg"],
    "risotto": ["rice", "cheese", "onion"],
}
for dish, ingredients in dishes.items():
    status = "safe" if allergies.isdisjoint(ingredients) else "NOT safe"
    print(dish, "-", status)
Output
pad thai - NOT safe
risotto - safe

3Does a booking clash with taken hours?

Pythoneditable
taken = {9, 10, 14}
request = range(11, 14)
if taken.isdisjoint(request):
    print("Booked 11:00 to 14:00")
else:
    print("Clash at", sorted(taken.intersection(request)))
Output
Booked 11:00 to 14:00

range(11, 14) is 11, 12 and 13: the end hour 14 is not included, so no clash.

Common mistakes

Reading the answer the wrong way round

True means no overlap. If you want "do they share something?", use not a.isdisjoint(b).

Pythoneditable
a = {"red"}
b = {"red", "blue"}
shares_something = not a.isdisjoint(b)
print(shares_something)
Output
True

Questions people ask

How do I check if two lists have any common element?

not set(a).isdisjoint(b) is True when at least one value appears in both.

Is an empty set disjoint with everything?

Yes. With no elements, it cannot share any.

Spotted a mistake on this page? Tell us