set.isdisjoint()
Returns True when this set and the other collection have no element in common, and False as soon as one is shared.
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
| Parameter | What it is |
|---|---|
otherrequired | A set or other iterable to compare with. |
Return value
True if there are no shared elements, otherwise False.
Examples
1Basic check
a = {1, 2, 3}
print(a.isdisjoint({4, 5}))
print(a.isdisjoint({3, 4}))True False
2Allergy check
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)pad thai - NOT safe risotto - safe
3Does a booking clash with taken hours?
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)))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).
a = {"red"}
b = {"red", "blue"}
shares_something = not a.isdisjoint(b)
print(shares_something)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.