This is another article about sets and set methods. If you haven’t read my previous ones, feel free to do so. Here they are:
Today we’ll be talking about set methods that return Boolean values, so True or False. We’ll learn how to check whether sets are disjoint or whether a set is a subset or superset of another.
You can also watch the video version of this article:
Disjoint Sets
The first method we’re going to talk about is isdisjoint. It returns True if the sets have no common elements, so their intersection is an empty set. Here we have two sets:
>>> asian_countries = {"China", "Japan", "Russia"}
>>> european_countries = {"Norway", "Russia", "Italy", "Belgium"}
These two sets are not disjoint because “Russia” belongs to both sets:
>>> asian_countries.isdisjoint(european_countries)
False
Let’s add another set:
>>> african_countries = {"Morocco", "RSA", "Kenya"}
Now we have disjoint sets:
>>> african_countries.isdisjoint(asian_countries)
True
Subsets and Supersets
The next two methods, issubset and issuperset are used to check whether a set is a subset or superset of another. Set x is a subset of set y if all elements of x also belong to y. Set x is a superset of y if all elements of y are contained in x. Here we have two sets:
>>> animals = {"toad", "earthworm", "starfish", "pig", "jellyfish", "penguin"}
>>> invertebrates = {"earthworm", "starfish", "jellyfish"}
Now let’s check how they are related to each other:
>>> animals.issubset(invertebrates)
False
>>> invertebrates.issubset(animals)
True
>>> animals.issuperset(invertebrates)
True
>>> invertebrates.issuperset(animals)
False
We can also use some shortcuts to check whether a set is a subset or a superset of another set – the comparison operators. Here they are:
x <= y | means x is a subset of y |
x < y | means x is a proper subset of y |
x >= y | means x is a superset of y |
x > y | means x is a proper superset of y |
A proper subset means that the subset contains fewer elements. If a subset is not a proper one, it may contain fewer elements or the same number of elements. In the latter case both sets contain the same elements. So, any set is a subset and a superset of itself, but not a proper one.
Let’s have a look at the two sets again, this time using the comparison operators:
>>> animals >= invertebrates # animals is superset of invertebrates
True
>>> animals > invertebrates # animals is proper superset of invertebrates
True
>>> animals >= animals # animals is superset of itself
True
>>> animals > animals # animals is not proper superset of itself
False
>>> animals <= invertebrates # animals is not subset of invertebrates
False
>>> invertebrates < animals # invertebrates is proper subset of animals
True
>>> invertebrates <= invertebrates # invertebrates is subset of itself
True
>>> invertebrates < invertebrates # invertebrates is not proper subset of itself
False