Learn AI
~40 minIn progress

Phase 1 · Programming Fundamentals

Sets & Collection Patterns

Use sets for uniqueness and fast membership, then combine lists, dicts, and sets in real recipes.

~40 min4 sections2 exercisesQuiz · pass 4/5
On this page
  1. 01What is a set?
  2. 02Membership and set operations
  3. 03List patterns you’ll reuse
  4. 04Dict + set recipes
  5. 05Mini challenge: skill matcher
  6. 06Try It
  7. 07Quiz

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.

Creating sets
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 ^.

Add, check, combine
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 only

discard(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.

Unique while keeping order
items = ["ada", "grace", "ada", "alan", "grace"]
unique = list(dict.fromkeys(items))
print(unique)  # ['ada', 'grace', 'alan']

# when order does not matter:
print(set(items))
Filter and transform
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.

Counting and key diffs
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 keys

Iterating 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).

challenge starter
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.

1.How do you create an empty set?
2.What happens to duplicates in a set?
3.Which operator returns items in both sets?
4.Why are sets good for membership checks?
5.Which structure best preserves first-seen order while removing duplicates?