Phase 1 · Programming Fundamentals
Sets & Collection Patterns
Use sets for uniqueness and fast membership, then combine lists, dicts, and sets in real recipes.
On this page
What is a set?
A set is an unordered collection of unique items. Duplicates are dropped automatically.
Create with curly braces {1, 2, 3} or set(...). An empty set must be set()—{} makes an empty dict.
tags = {"nlp", "cv", "nlp", "rl"}
print(tags) # duplicates removed
nums = set([3, 1, 4, 1, 5, 9, 3])
print(nums)
empty = set()
print(type(empty), type({}))Set items must be hashable (immutable): numbers, strings, tuples—not lists or dicts.
Membership and set operations
in is very fast on sets. Use add and discard/remove to update.
Combine sets with union |, intersection &, difference -, and symmetric difference ^.
skills = {"python", "git"}
skills.add("sql")
print("git" in skills)
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b) # union
print(a & b) # intersection
print(a - b) # in a but not b
print(a ^ b) # in one set onlydiscard(x) removes x if present and does nothing otherwise. remove(x) raises KeyError if missing.
List patterns you’ll reuse
Deduplicate while optionally preserving order. Filter and map with comprehensions.
When order does not matter and you only care about unique values, convert to a set.
items = ["ada", "grace", "ada", "alan", "grace"]
unique = list(dict.fromkeys(items))
print(unique) # ['ada', 'grace', 'alan']
# when order does not matter:
print(set(items))scores = [88, 55, 91, 70, 64]
passed = [s for s in scores if s >= 70]
labels = ["pass" if s >= 70 else "retry" for s in scores]
print(passed)
print(labels)Dict + set recipes
Group values, count keys, and compare key sets between dictionaries.
These patterns show up in EDA, feature checks, and simple analytics scripts.
words = ["ai", "ml", "ai", "nlp", "ml", "ai"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)
old = {"name": "Ada", "role": "eng"}
new = {"name": "Ada", "team": "AI", "role": "eng"}
print(set(new) - set(old)) # {'team'} new keys
print(set(old) & set(new)) # shared keysIterating a dict yields keys. set(my_dict) is the set of keys.
Practice
Mini challenge: skill matcher
You have required = {"python", "git", "sql"} and a candidate’s skills as a comma-separated input string. Print matched skills, missing skills, and whether they qualify (no missing skills).
required = {"python", "git", "sql"}
raw = input("Skills (comma-separated): ")
# TODO: build a set of candidate skills (strip + lower)
# print matched, missing, and qualifies True/False
Interactive
Try It in the browser
Powered by Pyodide
Create set a = {1,2,3,4,5} and b = {4,5,6,7}. Print union, intersection, and values only in a.
Output
—
Errors
—
Check understanding
Lesson quiz
Score 4/5 or higher to mark this day complete.