0
0
Pythonprogramming~5 mins

Subset and superset checks in Python

Choose your learning style9 modes available
Introduction
We use subset and superset checks to see if all items of one group are inside another group or if one group contains all items of another. This helps us compare collections easily.
Checking if all your friends are invited to a party list.
Verifying if a student's completed courses cover all required courses for graduation.
Making sure a shopping list is fully included in what a store has.
Confirming if a smaller set of permissions is included in a bigger set for user access.
Syntax
Python
set1.issubset(set2)
set1.issuperset(set2)

# Or using operators:
set1 <= set2  # subset check
set1 >= set2  # superset check
issubset() returns True if every item in set1 is also in set2.
issuperset() returns True if set1 contains every item in set2.
Examples
a is a subset of b because all items in a are in b.
Python
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b))  # True
print(b.issubset(a))  # False
x is a superset of y because x contains all items in y.
Python
x = {4, 5, 6}
y = {5, 6}
print(x.issuperset(y))  # True
print(y.issuperset(x))  # False
Using operators, <= checks subset and >= checks superset.
Python
s1 = {10, 20}
s2 = {10, 20, 30}
print(s1 <= s2)  # True
print(s2 >= s1)  # True
Sample Program
This program checks if all invited friends are actually in the party guest list using subset and superset checks.
Python
friends_invited = {"Alice", "Bob", "Charlie"}
party_guests = {"Alice", "Bob", "Charlie", "David"}

# Check if all invited friends are in the guest list
all_invited_coming = friends_invited.issubset(party_guests)

# Check if guest list includes all invited friends
guest_list_covers_invited = party_guests.issuperset(friends_invited)

print(f"All invited friends coming? {all_invited_coming}")
print(f"Guest list covers all invited? {guest_list_covers_invited}")
OutputSuccess
Important Notes
Subset and superset checks work only with sets, not lists or other types.
The operators <= and >= are shorthand for issubset() and issuperset(), but only work with sets.
Empty set is a subset of every set, and every set is a superset of the empty set.
Summary
Subset means all items of one set are inside another set.
Superset means one set contains all items of another set.
Use issubset(), issuperset() or <=, >= operators to check these.