Sub topic 7
Comparing sets: subsets, supersets, disjoint sets
This chapter assumes you can create sets, test membership with in, and combine sets with |, &, - and ^. It also assumes you know that set elements must be hashable. Here you will learn how to ask questions about the relationship between two sets: is one contained in the other, are they identical, or do they share nothing?
The relationships a pair of sets can have
Two sets a and b fall into one of a few relationships:
- They have exactly the same elements (equal).
- Every element of
ais inb, andbhas more (ais a proper subset ofb). - Every element of
bis ina, andahas more (ais a proper superset ofb). - They share no elements (disjoint).
- They overlap partially, so none of the above applies.
Python provides operators and methods for each of these.
| Question | Operator | Method |
|---|---|---|
| Is `a` a subset of `b`? | `a <= b` | `a.issubset(b)` |
| Is `a` a proper subset of `b`? | `a < b` | none |
| Is `a` a superset of `b`? | `a >= b` | `a.issuperset(b)` |
| Is `a` a proper superset of `b`? | `a > b` | none |
| Do `a` and `b` have the same elements? | `a == b` | none |
| Do `a` and `b` share no elements? | none | `a.isdisjoint(b)` |
A proper subset is a subset that is not equal to the other set. The symbols point toward the smaller set. small <= big reads as "small is contained in big".
Subset and superset operators
small = {1, 2}
big = {1, 2, 3}
print(small <= big) # True, every element of small is in big
print(small < big) # True, and big has extra elements
print(big >= small) # True
print(big > small) # True
print(small <= small) # True, a set is a subset of itself
print(small < small) # False, but not a proper subset of itself
print(small == {2, 1}) # True, order does not matterThe difference between <= and < matters most at the boundary. Use <= when "the same set" should count as a match. Use < when you need the other set to have something extra.
The empty set and equality
The empty set is a subset of every set, including itself. It is a proper subset of every non-empty set.
empty = set()
data = {"x", "y"}
print(empty <= data) # True
print(empty < data) # True
print(empty <= empty) # True
print(empty < empty) # False
print(data >= empty) # TrueEquality compares elements using the same hash and equality rules as membership tests. Two values that are equal and have equal hashes count as the same element:
print({1, 2} == {2, 1}) # True
print({1} == {1.0}) # True, because 1 == 1.0 and hash(1) == hash(1.0)
print({1, True} == {1}) # True, because True == 1
print({1} == [1]) # False, a set never equals a listThe last line shows that == between a set and a non-set is simply False. It does not raise an error.
Disjoint sets
Two sets are disjoint when their intersection is empty. isdisjoint answers this directly:
admins = {"ana", "bo"}
guests = {"cy", "di"}
staff = {"bo", "ed"}
print(admins.isdisjoint(guests)) # True
print(admins.isdisjoint(staff)) # False, "bo" is in both
print(admins.isdisjoint(set())) # True, the empty set shares nothingYou could write not (admins & guests) and get the same answer. isdisjoint is the better choice. It reads more clearly, and it stops at the first shared element. The & version builds a whole new set first.
Partial order: not every pair is comparable
Numbers have a total order: for any two numbers, either x <= y or y <= x is true. Sets do not. Sets are only partially ordered, so two sets can be unrelated.
a = {1, 2}
b = {2, 3}
print(a < b) # False
print(a > b) # False
print(a == b) # False
print(a <= b or b <= a) # False, neither contains the other
print(a.isdisjoint(b)) # False, they overlap on 2Every comparison here is False, yet the sets are not equal. This has two consequences.
First, not (a <= b) does not mean a > b. It only means that a is not contained in b. The sets might be unrelated, or b might be contained in a.
Second, sorting a list of sets with sorted() or .sort() is unreliable. The sort algorithm assumes a total order, and it relies on < giving consistent answers. With unrelated sets it gives a result that depends on the input order. If you want to order sets, pick a key, such as size:
sets = [{1, 2, 3}, {9}, {4, 5}]
print(sorted(sets, key=len)) # [{9}, {4, 5}, {1, 2, 3}]Operators versus methods: what each accepts
The comparison operators need a set (or frozenset) on both sides. The methods issubset, issuperset and isdisjoint accept any iterable, which saves you from converting first.
required = {"name", "email"}
print(required.issubset(["name", "email", "age"])) # True
try:
required <= ["name", "email", "age"]
except TypeError as e:
print(e) # '<=' not supported between instances of 'set' and 'list'Methods that take an iterable build a temporary set from it internally, so the cost is the same as converting it yourself. Use the method when the other side is a list, tuple, string or generator. Use the operator when both sides are already sets, since the operator catches accidental type mistakes.
Because iterating a dictionary yields its keys, the methods work well for key checks:
user = {"name": "Ada", "email": "[email protected]", "age": 36}
print(required.issubset(user)) # True, all required keys are present
print(user.keys() >= required) # True, dict key views support set comparisons
print(required.isdisjoint(user)) # FalseA dictionary key view (the object returned by .keys()) supports the same comparison operators as a set. This makes user.keys() >= required a compact "has all required keys" check.
Mixing set and frozenset
set and frozenset can be compared with each other. Equality and containment work on elements and ignore which of the two types holds them.
print({1, 2} == frozenset({1, 2})) # True
print({1, 2} <= frozenset({1, 2, 3})) # True
print(frozenset({1}) < {1, 2}) # TrueThis is useful when you keep a collection of frozensets as dictionary keys but build the query as a normal set.
A chain check
A common task is checking that a sequence of sets grows or shrinks step by step. Compare neighbours with zip:
stages = [{1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}]
grows = all(x < y for x, y in zip(stages, stages[1:]))
print(grows) # True
broken = [{1}, {2}, {1, 2}]
print(all(x <= y for x, y in zip(broken, broken[1:]))) # False, {1} is not in {2}Python allows chained comparisons such as a < b < c, and for sets this means a < b and b < c. It is valid, but a longer chain is easier to read with all(...).
Common mistakes
- Using
<when you meant<=.required < givenisFalsewhen the two sets are equal. For "has at least these", use<=. - Assuming
not a <= bmeansa > b. The sets may be unrelated. See the partial order section above. - Comparing a set with a list using an operator. This raises
TypeErrorfor<,<=,>and>=. Use the method form or convert the list withset(...). - Expecting
==to raise on a type mismatch.{1} == [1]is justFalse, which can hide a bug where you forgot to convert. - Testing disjointness with
len(a & b) == 0. It works, but it builds a full intersection set whena.isdisjoint(b)stops at the first shared element. - Forgetting that the empty set is a subset of everything. A check such as
required <= givenpasses whenrequiredis empty. If an empty requirement should count as an error, test for it separately.
Worked example: validating a configuration
This example combines the comparison tools. It checks a submitted configuration against required, optional and forbidden keys.
REQUIRED = {"host", "port"}
OPTIONAL = {"timeout", "retries"}
FORBIDDEN = {"password"}
def check(config):
keys = set(config)
problems = []
if not REQUIRED <= keys:
problems.append(f"missing: {sorted(REQUIRED - keys)}")
if not keys.isdisjoint(FORBIDDEN):
problems.append(f"forbidden: {sorted(keys & FORBIDDEN)}")
unknown = keys - REQUIRED - OPTIONAL - FORBIDDEN
if unknown:
problems.append(f"unknown: {sorted(unknown)}")
return problems
print(check({"host": "a", "port": 1, "timeout": 5})) # []
print(check({"host": "a", "password": "x", "color": 1}))
# ["missing: ['port']", "forbidden: ['password']", "unknown: ['color']"]Each check uses the tool that matches the question: a subset test for completeness, a disjoint test for a ban list, and a difference for finding strays. The sorted(...) calls make the messages stable, since set iteration order is not guaranteed.
Exercises
Exercise
Given a = {1, 2, 3} and b = {3, 2, 1}, what do a <= b, a < b and a == b return, and why?
Show answer
They return True, False and True. The sets have the same elements, so each is a subset of the other, which makes <= true and == true. < requires a proper subset, meaning b must contain at least one element that a lacks, so it is false.
Exercise
For a = {1, 2} and b = {2, 3}, a < b and a > b are both False. Does that mean a == b? What does it show about how sets are ordered?
Show answer
No. a == b is also False. Neither set contains the other, so they are unrelated. Sets are only partially ordered, which means two sets can be incomparable. Because of this, not (a < b) does not imply a >= b, and sorting a list of sets with the default < is unreliable.
Exercise
Write a one-line expression that is True when the list tags contains every item in the set {"python", "sets"}, without converting the set to a list. Then say why {"python", "sets"} <= tags would fail.
Show answer
{"python", "sets"}.issubset(tags). The operator <= requires both operands to be sets, so with a list on the right it raises TypeError. The method issubset accepts any iterable and converts it internally.
Exercise
What does set().isdisjoint(set()) return, and what does set() < set() return?
Show answer
isdisjoint returns True, because two empty sets share no elements. set() < set() returns False, because the empty set is equal to itself and so is not a proper subset of itself. set() <= set() is True.