Python Tutorial
Python Join Sets
union() and | combine sets. intersection() keeps items in both. difference() keeps items only in the first.
Union, Intersection, Difference
All return a new set. update() versions change in place.
set1 = {"a", "b", "c"}
set2 = {1, 2, "c"}
print(set1.union(set2))
print(set1 | set2)
print(set1.intersection(set2))
print(set1.difference(set2))
print(set1.symmetric_difference(set2))📘 Real-World Deep Dive
Set algebra (<code>|</code>, <code>&</code>, <code>-</code>, <code>^</code>) is the most expressive filter group in Python. Pair it with <code>set.union/update/intersection/difference</code> to write one-line filters that read like SQL.
Real-Life Scenario
Build three overlapping user groups, then derive active subscribers, never-tried-premium, and users who cancelled but paid once.
Real-Life Example
subscribed = {"ada", "bo", "cy", "de"}
free = {"bo", "cy", "de", "frank"}
premium = {"ada", "ed"}
cancelled = {"ed"}
active_subs = subscribed | free # union of anyone ever subscribed
tried_premium = premium & free # tried premium while on free
never_premium = active_subs - premium # active but never on premium
paid_then_left = premium & cancelled
Expected Output
active_subs : {'frank', 'de', 'cy', 'bo', 'ada'}
tried_premium : {'bo'}
never_premium : {'frank', 'cy', 'de', 'bo'}
paid_then_left : {'ed'}Common mistakes
s | treturns a new set;s |= tupdates in place. Mixing them silently changes performance.- The symmetric difference
s ^ treturns elements in exactly one operand — a useful "exclusive or" for fingerprints. - Empty set algebra returns an empty set, not
None— fine, just don't expect truthiness on its own.
🚀 Performance & Best Practices
- Set operations are O(min(len(a), len(b))) in CPython; iterate in the smaller-side-first order for big sets.
- Build set composites up-front and use union/non-overlapping membership tests in hot paths.
- Reverse iteration is cheap on hash sets — don't sort first.
🧪 Try It Yourself
- Build a
segment(users)that returns a dict of "active", "trial", "churned" counters. - Replace set algebra with a SQL
UNION/EXCEPTquery and benchmark. - For very large lists, use
numpyarrays + boolean masks instead of sets.