Python Set Methods
Set methods test how one set relates to another set. These methods answer with True or False.
Test for a subset
A subset fits fully inside a bigger set.
small = {1, 2}
big = {1, 2, 3}
print(small.issubset(big))
print(small <= big)Test for a superset
A superset holds every item of a smaller set.
big = {1, 2, 3}
small = {1, 2}
print(big.issuperset(small))
print(big >= small)Test for no overlap
Disjoint means the sets share no items.
a = {1, 2}
b = {3, 4}
c = {2, 5}
print(a.isdisjoint(b))
print(a.isdisjoint(c))A method accepts a list
The issubset() method accepts a list here.
print({"red"}.issubset(["red", "blue"]))Copy a set
A copy can change on its own.
original = {"a", "b"}
backup = original.copy()
backup.add("c")
print(sorted(original))
print(sorted(backup))Example
required = {"flour", "eggs", "milk"}
pantry = {"flour", "sugar", "eggs", "milk", "butter"}
print(required.issubset(pantry))
print(pantry.issuperset(required))
print(sorted(pantry - required))Key points
- Subset: every item of the first set is in the second set
- Superset: the first set holds every item of the second set
- Use isdisjoint() to test if two sets share no items
- Use copy() to make a separate copy of a set
In this example, required holds the ingredients you need. The pantry set holds the ingredients you have. The issubset() call checks that each needed item is in the pantry. The answer is True, so you can bake. The issuperset() call asks the same question in reverse. The last line prints the extra pantry items in a stable order.
Note
Methods accept any iterable like a list — operators need a set on both sides
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does {1, 2}.isdisjoint({3, 4}) give?