Set Operations Examples
Short, runnable programs that show python set operations in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Set Operations lesson.
1Checking requirements with issubset
required <= skills is a single readable test for "has every required skill", and required - skills lists exactly what is still missing.
required = {"python", "sql", "git"}
applicants = [
("Asha", {"python", "sql", "git", "docker"}),
("Ben", {"python", "git"}),
("Cara", {"sql", "excel"}),
]
for name, skills in applicants:
if required <= skills:
print(name, "qualifies")
else:
print(name, "is missing", sorted(required - skills))Expected outputAsha qualifies
Ben is missing ['sql']
Cara is missing ['git', 'python']
2Removing duplicate e-mails, keeping the first of each
Clean each address first (strip spaces, lowercase) so that near-identical ones count as repeats. The seen set makes each check fast, and a separate list keeps the order. The one-line dict.fromkeys version gives the same result.
emails = ["Asha@x.com", "ben@x.com", "asha@x.com ", "Cara@x.com", "BEN@x.com"]
seen = set()
unique = []
for email in emails:
clean = email.strip().lower()
if clean not in seen:
seen.add(clean)
unique.append(clean)
print(unique)
cleaned = [email.strip().lower() for email in emails]
print(list(dict.fromkeys(cleaned)))Expected output['asha@x.com', 'ben@x.com', 'cara@x.com']
['asha@x.com', 'ben@x.com', 'cara@x.com']
3frozenset keys for two-way distances
The distance from Pune to Mumbai equals the distance back, so the pair does not have order. A frozenset of the two cities is the same key in both directions, and each route is stored only once.
distance = {
frozenset({"Pune", "Mumbai"}): 150,
frozenset({"Pune", "Nashik"}): 210,
frozenset({"Mumbai", "Nashik"}): 170,
}
def km(a, b):
return distance[frozenset({a, b})]
print(km("Pune", "Mumbai"), km("Mumbai", "Pune"))
print(km("Nashik", "Pune"))
print(len(distance), "routes stored once each")Expected output150 150
210
3 routes stored once each
4Attendance across several days
set.intersection(*days) finds the people present on every day, and set().union(*days) everyone who came at least once. Chained subtraction finds people who attended only one day.
monday = {"Asha", "Ben", "Cara", "Dev"}
tuesday = {"Ben", "Cara", "Dev", "Eli"}
wednesday = {"Cara", "Dev", "Eli", "Fay"}
days = [monday, tuesday, wednesday]
every_day = set.intersection(*days)
any_day = set().union(*days)
print("Every day:", sorted(every_day))
print("At least once:", sorted(any_day))
print("Missed a day:", sorted(any_day - every_day))
print("Only on Monday:", sorted(monday - tuesday - wednesday))Expected outputEvery day: ['Cara', 'Dev']
At least once: ['Asha', 'Ben', 'Cara', 'Dev', 'Eli', 'Fay']
Missed a day: ['Asha', 'Ben', 'Eli', 'Fay']
Only on Monday: ['Asha']
5Set comprehensions on e-mail addresses
A set comprehension collects values and drops repeats in one expression. The first set holds the different domains; the second holds the user names longer than three letters, tidied with title().
emails = ["asha@school.org", "ben@mail.com", "cara@school.org", "dev@mail.com", "eli@corp.io"]
domains = {address.split("@")[1] for address in emails}
print(sorted(domains))
names = [address.split("@")[0] for address in emails]
long_names = {name.title() for name in names if len(name) > 3}
print(sorted(long_names))
print(len(emails), "addresses,", len(domains), "domains")Expected output['corp.io', 'mail.com', 'school.org']
['Asha', 'Cara']
5 addresses, 3 domains
6How similar are two texts?
Dividing the size of the intersection by the size of the union (the Jaccard score) gives 1.0 for identical word sets and 0.0 when they share nothing. Recommendation and duplicate-detection tools use this idea.
def similarity(first, second):
a = set(first.lower().split())
b = set(second.lower().split())
return len(a & b) / len(a | b)
print(similarity("red apple pie", "green apple pie"))
print(round(similarity("Red apple pie", "green apple tart"), 2))
print(similarity("tea", "coffee"))
print(similarity("tea time", "Time TEA"))Expected output0.5
0.2
0.0
1.0
Practise next
Python Set Operations exercises → Back to the lesson
Python Sets examplesPython Dictionaries examplesPython collections Module examplesPython List Comprehensions examples