logo
15

Sets

⏱️ 25 min

Sets: Fast Deduplication and Set Operations

What You Might Be Wondering

"I can deduplicate with a list too. Why bother with sets?"

Sets are typically faster for membership checks and deduplication. And they natively support union, intersection, and difference — no extra code needed.

One-Line Definition

A set is an unordered collection of unique elements, great for deduplication and set math.

Real-Life Analogy

Two class rosters and you need to find students in both? A set intersection does it in one line.

Minimal Working Example

tags = {"python", "ai", "python"}
print(tags)  # {'python', 'ai'}

Basic Operations

s = {1, 2, 3}
s.add(4)
s.remove(2)
s.discard(99)  # no error if missing
print(s)

Set Operations

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)  # union
print(a & b)  # intersection
print(a - b)  # difference
print(a ^ b)  # symmetric difference

Quick Quiz (5 min)

  1. Deduplicate a list of usernames.
  2. Find the intersection and difference of two user groups.
  3. Check whether a specific element is in a set.

Quiz Rubric & Grading Criteria

  • Direction: write runnable code that covers the core requirements and edge cases from the prompt.
  • Criterion 1 (Correctness): main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.

Take-Home Task

Implement a "permission checker" function:

  • required_perms
  • user_perms
  • Output the list of missing permissions

Acceptance Criteria

You can independently:

  • Use sets for deduplication
  • Perform union, intersection, and difference operations
  • Explain when to use a set vs. a list

Common Errors & Debugging Steps (Beginner Edition)

  • Error message looks like gibberish: read the last line for the error type (TypeError, NameError, etc.), then trace back to the offending line.
  • Not sure what a variable holds: drop a temporary print(variable, type(variable)) to check.
  • Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.

Common Misconceptions

  • Misconception: {} creates an empty set.

  • Reality: {} creates an empty dict. Use set() for an empty set.

  • Misconception: sets can hold any type of element.

  • Reality: elements must be hashable. Lists and dicts can't go in a set.