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 ^. Here you will learn how to ask questions about the relationship between two sets: does one contain the other, are they identical, or do they share nothing?
The relationships
Every comparison between two sets falls into one of a few cases. Take two sets A and B.
Ais a subset ofBif every element ofAis also inB.Ais a superset ofBif every element ofBis also inA.Ais a proper subset or superset if the two sets are not equal.AandBare disjoint if they share no elements.
The empty set is a subset of every set, and every set is a subset of itself.
Operators for comparison
Python uses the comparison operators for these tests. They read like the math symbols for subset and superset.
| Expression | Meaning |
|---|---|
| `a <= b` | `a` is a subset of `b` |
| `a < b` | `a` is a proper subset of `b` |
| `a >= b` | `a` is a superset of `b` |
| `a > b` | `a` is a proper superset of `b` |
| `a == b` | same elements |
| `a != b` | different elements |
small = {1, 2}
big = {1, 2, 3}
print(small <= big) # True, subset
print(small < big) # True, proper subset
print(big >= small) # True, superset
print(small.isdisjoint({7, 8})) # True, no shared elementsNotice that small <= small is True, but small < small is False. A set is never a proper subset of itself.
Methods for comparison
Each ordering operator has a method form: issubset() and issuperset(). The method versions accept any iterable, not only a set. The operators require both sides to be sets.
required = {"read", "write"}
granted = ["read", "write", "delete"]
print(required.issubset(granted)) # True, a list works with the method
print(required <= set(granted)) # True, the operator needs a set on both sides
try:
print(required <= granted)
except TypeError as e:
print(e) # '<=' not supported between instances of 'set' and 'list'There is no method for proper subset or proper superset. Use < and > for those.
isdisjoint() is also a method only. It returns True when the intersection is empty. It can stop at the first shared element, so it is cheaper than building a & b and checking whether the result is empty.
a = {1, 2, 3}
print(a.isdisjoint({4, 5})) # True
print(a.isdisjoint({3, 4})) # False, 3 is shared
print(a.isdisjoint(set())) # True, the empty set shares nothingComparisons are not a total order
Numbers always compare: for any two, one is smaller, larger or equal. Sets do not work that way. Two sets can each have elements the other lacks, so neither is a subset of the other.
x = {1, 2}
y = {2, 3}
print(x < y) # False
print(x > y) # False
print(x == y) # FalseAll three results are False. Do not read not (x < y) as meaning x >= y.
A related effect: sorting a list of sets with sorted() does not give a meaningful order, because < is not a total order. The result depends on the starting order of the list.
Common errors
- Using
<when you mean<=. If you want to allow equal sets, use<=. - Comparing a set with a list using an operator.
{1, 2} <= [1, 2, 3]raisesTypeError. Convert the list withset()or useissubset(). - Expecting
==to compare order.{1, 2} == {2, 1}isTrue. Sets have no order to compare. - Assuming an empty result means a bug.
set() <= anythingisTrue, so a check against an empty required set always passes.
A worked example
A common use is checking that a user has every permission an action needs.
def can_run(required, granted):
return set(required) <= set(granted)
print(can_run({"read"}, {"read", "write"})) # True
print(can_run({"read", "admin"}, {"read"})) # False
print(can_run([], {"read"})) # True, nothing is requiredExercise
Given a = {1, 2, 3} and b = {1, 2, 3}, what do a <= b, a < b and a.isdisjoint(b) return?
Show answer
a <= b is True because equal sets are subsets of each other. a < b is False because a proper subset must not equal b. a.isdisjoint(b) is False because the sets share all their elements.
Exercise
Why does {1, 2} <= [1, 2, 3] raise a TypeError, and how do you fix it in two ways?
Show answer
The ordering operators require both operands to be sets. Fix it by converting the list, {1, 2} <= set([1, 2, 3]), or by using the method, {1, 2}.issubset([1, 2, 3]), which accepts any iterable.