Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.isdisjoint() method

Reference for Python set.isdisjoint(): test whether two collections share no elements, accepted argument types, empty sets and how it differs from intersection().

The isdisjoint() method of a set returns True when the set and another collection have no element in common, and False as soon as they share at least one. Two sets that share nothing are called disjoint.

It is the cheapest way to ask "do these overlap?" because it can stop at the first shared element, without building the intersection set.

Python
{1, 2, 3}.isdisjoint({4, 5})   # True
{1, 2, 3}.isdisjoint({3, 4})   # False

Try it

Python Do two schedules clash?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python isdisjoint() versus intersection()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
set.isdisjoint(other)
Name Description
other Any iterable. Its items must be hashable, because they are looked up in the set.

Return value: True if the two collections have no common element, otherwise False.

Raises: TypeError if other is not iterable, or contains unhashable items that need to be compared.

Usage notes

  • Accepts any iterable. Unlike the & operator, which needs two sets, the method accepts lists, tuples, strings and other iterables. Python converts them as needed.
  • Empty sets are disjoint from everything, including other empty sets, so set().isdisjoint(set()) is True.
  • Short-circuits. Python returns False on the first shared element, so it is faster than not (a & b) when sets are large and overlap early.
  • Does not change either set. It only answers a question.
  • Iterate the smaller side. When other is a set, CPython loops over the smaller one and checks membership in the larger one.
  • Not the same as !=. Two different sets can still overlap. Use isdisjoint() only for "nothing shared".
  • Equal non-empty sets are never disjoint, since they share every element.