Python Tutorial
Python Set Methods
Sets have methods for adding, removing, and comparing collections.
isdisjoint, issubset, issuperset
Compare two sets.
a = {1, 2, 3}
b = {1, 2, 3, 4}
print(a.issubset(b))
print(b.issuperset(a))
print(a.isdisjoint({9, 8}))📘 Real-World Deep Dive
The "mathematical set" methods (<code>union/intersection/difference/symmetric_difference</code>) and the mutation helpers (<code>add/discard/remove/update/pop</code>) form a small, complete vocabulary for filtering and grouping.
Real-Life Scenario
Tag-based search: a user has positive and negative tag lists; a candidate has a tag set. We score by how well they match.
Real-Life Example
from typing import Iterable
def score(prefer: set[str], avoid: set[str], cand: set[str]) -> int:
hits = len(prefer & cand) # positive matches
misses = len(avoid & cand) # unwanted matches
surplus = len(prefer - cand) # unmatched positives (informative)
return hits * 2 - misses * 3 - surplus
candidates = [
{"python", "django", "postgres", "redis"},
{"python", "flask", "sqlite"},
{"javascript", "node", "postgres"},
{"python", "django", "graphql"},
]
prefer = {"python", "django"}
avoid = {"javascript", "redis"}
ranked = sorted(candidates, key=lambda c: -score(prefer, avoid, c))
for i, cand in enumerate(ranked, 1):
common_pref = sorted(prefer & cand)
conflict = sorted(avoid & cand)
print(f"#{i} score={score(prefer, avoid, cand):>3} \u00b7 likes={common_pref} \u00b7 conflicts={conflict}")Expected Output
#1 score= 5 · likes=['django', 'python'] · conflicts=[]
#2 score= 1 · likes=['django', 'python'] · conflicts=[]
#3 score= -3 · likes=['python'] · conflicts=['redis']
#4 score= -4 · likes=[] · conflicts=['javascript']Common mistakes
set.remove(x)raisesKeyErrorif missing;set.discard(x)silently does nothing.- Sets don't allow duplicates; if you need order + uniqueness, use
dict.fromkeys(seq)(Python 3.7+). - Set mutation during iteration raises
RuntimeError— copy withset(xs)first if you need to filter.
🚀 Performance & Best Practices
s.update(t)is in-place and fast;s = s | tcreates a new set.{*a, *b}is the readable, fast form of union.- Large subsets shrink faster with
want &= havethan rebuilding.
🧪 Try It Yourself
- Replace the manual scoring with a weighted dictionary per tag.
- Implement top-K unique candidates using a heap.
- Benchmark set operations vs. list comprehensions on 100 k tags.