>>> s = {1, 2, 3, 4} >>> t = {'Alice', 'Bob'} >>> s.isdisjoint(t) True

## Syntax

set.isdisjoint(set)

## Return Value of set.isdisjoint()

## Advanced Examples set.isdisjoint()

We start with a simple and trivial example of two disjoint sets:

>>> {1, 2, 3}.isdisjoint({'Alice', 'Bob'}) True

? Can you also pass a list as an argument to the `set.isdisjoint()`

method? The answer is yes—the method takes any iterable.

>>> {1, 2, 3}.isdisjoint(['Alice', 'Bob']) True

Let’s have an example of a non-disjoint set combination that intersect in one element—can you figure out which?

>>> {1, 2, 3}.isdisjoint({'Alice', 'Bob', 1}) False

Are two empty sets disjoint? Yes—they have no common elements. The intersection between two empty sets is empty, so they are disjoint!

>>> set().isdisjoint(set()) True

The same holds if one of the sets is non-empty:

>>> set().isdisjoint({1, 2, 3}) True >>> {1, 2, 3}.isdisjoint(set()) True

Can we pass multiple set arguments into the `set.isdisjoint()`

method? No! It only takes one argument.

>>> {1, 2, 3}.isdisjoint({4, 5}, {'Alice', 'Bob'}) Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> {1, 2, 3}.isdisjoint({4, 5}, {'Alice', 'Bob'}) TypeError: isdisjoint() takes exactly one argument (2 given)

## What is the Time Complexity of set.isdisjoint() in Python?

import matplotlib.pyplot as plt import time sizes = [i * 10**5 for i in range(50)] runtimes = [] for size in sizes: s = set(range(size)) t = set(range(0, size, 2)) # Start track time ... t1 = time.time() s.isdisjoint(t) t2 = time.time() # ... end track time runtimes.append(t2-t1) plt.plot(sizes, runtimes) plt.ylabel('Runtime (s)') plt.xlabel('Set Size') plt.show()

The runtime complexity feels constant. Only if we slightly modify the experiment to ensure that the sets are not disjoint will we see an increase of the runtime complexity with increasing set sizes:

import matplotlib.pyplot as plt import time sizes = [i * 10**5 for i in range(50)] runtimes = [] for size in sizes: s = set(range(size)) t = set(range(size, 2* size, 1)) # Start track time ... t1 = time.time() s.isdisjoint(t) t2 = time.time() # ... end track time runtimes.append(t2-t1) plt.plot(sizes, runtimes) plt.ylabel('Runtime (s)') plt.xlabel('Set Size') plt.show()

## Other Python Set Methods

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.