PythonMastery

Check subset and superset in Python

Check whether every item of one set is in another with issubset(), issuperset() or the <= and >= operators, plus isdisjoint().

Set a is a subset of set b when every item of a is also in b. Then b is a superset of a.

The program

python
required = {"python", "sql"}
ada_skills = {"python", "sql", "git", "docker"}
linus_skills = {"c", "git", "python"}

print("Ada has all required skills:", required.issubset(ada_skills))
print("Linus has all required skills:", required.issubset(linus_skills))
print("Ada's skills cover the list:", ada_skills.issuperset(required))

missing = required - linus_skills
print("Linus is missing:", missing)
output
Ada has all required skills: True
Linus has all required skills: False
Ada's skills cover the list: True
Linus is missing: {'sql'}

How it works

The operators, and isdisjoint()

python
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}

print(a <= b)   # subset
print(b >= a)   # superset
print(a < b)    # proper subset: a is in b, and b has more
print(a < a)    # a set is a subset of itself, but not a proper one
print(a.isdisjoint({7, 8}))  # True when there are no shared items
output
True
True
True
False
True

The empty set set() is a subset of every set. Write set(), not {}: {} creates an empty dictionary.

Learn the idea: Sets: Unordered, Unique, Lightning Fast