Lesson 11 — Unique Collections
Sets
A Python set stores unique elements with O(1) membership testing. Set operations — union, intersection, difference — are built into the language and often replace loops.
PYTHON — Set basics
# Creation:
courses = {"Java", "Python", "SQL", "Java"} # duplicate removed silently
print(courses) # order not guaranteed: {'Java', 'Python', 'SQL'}
print(len(courses)) # 3
# Empty set — MUST use set(), not {} (that creates a dict!):
empty_set = set()
empty_dict = {} # this is a dict, not a set
# From a list (deduplication):
marks_with_dupes = [65, 72, 80, 65, 72, 91]
unique_marks = set(marks_with_dupes)
print(unique_marks) # {65, 72, 80, 91}
PYTHON — Set operations
courses = {"Java", "Python", "SQL"}
# Adding and removing:
courses.add("C#")
courses.add("Java") # ignored — already exists
courses.discard("Ruby") # no error if not found
courses.remove("SQL") # KeyError if not found
print(courses) # {'Java', 'Python', 'C#'}
# Membership — O(1) average (much faster than list for large sets):
print("Python" in courses) # True
print("Kotlin" in courses) # False
Set Algebra
PYTHON — Set algebra
morning = {"Thandi", "Sipho", "Lerato", "Bongani"}
afternoon = {"Bongani", "Zanele", "Sipho", "Nomsa"}
# Union — all unique elements from both:
all_learners = morning | afternoon
# or: morning.union(afternoon)
print(f"All: {all_learners}")
# Intersection — elements in both:
both_sessions = morning & afternoon
# or: morning.intersection(afternoon)
print(f"Both sessions: {both_sessions}") # {'Bongani', 'Sipho'}
# Difference — in morning but not afternoon:
morning_only = morning - afternoon
print(f"Morning only: {morning_only}")
# Symmetric difference — in one but not both:
exclusive = morning ^ afternoon
print(f"Exclusive: {exclusive}")
# Subset and superset:
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
print(a.issubset(b)) # True — a <= b
print(b.issuperset(a)) # True — b >= a
Practice Task
Your Turn
You have two lists of email addresses — one from a morning session signup and one from an afternoon session. Use sets to find: (1) all unique addresses, (2) addresses in both sessions, (3) people who only attended morning, (4) people who attended exactly one session. Deduplicate both lists before processing.
Common Mistakes
- Empty set is
set()not{}— curly braces without key:value pairs create an empty dict. - Sets are unordered — no index access, no slicing.
- Mutable objects (lists, dicts) cannot be set elements — they are not hashable.
remove()raises KeyError for missing elements;discard()is safe.
Professional Tip
Use a set for O(1) membership testing whenever you have more than a handful of elements. Checking 'is this user in the blocked list?' over a set of 100,000 items is just as fast as over 10 items.
Mini Quiz
Which Python expression creates an empty set?
set() creates an empty set. {} creates an empty dictionary — a common mistake. Always use set() for an empty set.