MOD-11 · Sequence #11 · Python Collections

Python Sets

Sets are unordered collections of unique, hashable objects backed by hash tables. They provide average O(1) time complexity for additions, removals, and membership checks, along with mathematical set operations (union, intersection, difference).

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b)  # Intersection: {3}
print(a | b)  # Union: {1, 2, 3, 4, 5}

Core Principles & Mental Models

1. Hash Table Mechanics & O(1) Lookups

Why Sets Beat Lists for Membership Checks

  • Under the hood, Python sets are implemented as open-addressing hash tables.
  • To insert an element, Python computes `hash(element)` and maps it to a bucket index in memory.
  • Looking up an item `x in my_set` is an average O(1) constant time operation, compared to O(N) linear time for lists.
registered = {"[email protected]", "[email protected]"}
print("Is bob registered?", "[email protected]" in registered)  # O(1) instant lookup
💡 Key Takeaway: Always use sets when deduplicating values or performing repeated membership tests.

2. Mathematical Set Algebra

Union, Intersection, Difference, Symmetric Difference

  • Union (|): Elements present in either set.
  • Intersection (&): Elements present in both sets.
  • Difference (-): Elements in set A but not in set B.
  • Symmetric Difference (^): Elements in exactly one of the sets, but not both.
group_a = {1, 2, 3, 4}
group_b = {3, 4, 5, 6}
print("Union:", group_a | group_b)         # {1, 2, 3, 4, 5, 6}
print("Intersection:", group_a & group_b)  # {3, 4}
print("Difference (A-B):", group_a - group_b) # {1, 2}
print("Symmetric Diff:", group_a ^ group_b)   # {1, 2, 5, 6}
💡 Key Takeaway: Set algebra operators make complex filtering and grouping operations trivial and high-performance.

Interactive Walkthrough Examples

Deduplicating While Preserving Identity (Basic)

Finding unique items and common intersections between two course rosters.

cs101 = {"Alice", "Bob", "Charlie", "David"}
math201 = {"Charlie", "David", "Eve", "Frank"}

both_courses = cs101 & math201
only_cs = cs101 - math201
print("Taking both:", sorted(both_courses))
print("Taking only CS101:", sorted(only_cs))

Explanation: Set intersections and differences operate in O(min(len(s), len(t))) time.

Common Misconceptions & Exam Traps

Common Pitfall: Creating an Empty Set with `{}`

{} is reserved syntax for creating an empty dictionary due to backward compatibility.

Buggy Code
empty_set = {}  # Creates an empty dict, NOT a set!
print(type(empty_set))  # <class 'dict'>
Correct Solution
empty_set = set()  # The correct syntax for empty sets
print(type(empty_set))  # <class 'set'>

Exam Trap Note: Exam question: "What is `type({})`?" The answer is dict, not set.

Conceptual Knowledge Self-Check Quiz

Q1: How do you instantiate an empty set in Python?

  1. {}
  2. set()
  3. []
  4. set({})

`set()` creates an empty set. `{}` creates an empty dictionary.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Only store hashable (immutable) objects in sets; lists and dicts cannot be elements of sets.
  • ✅ Use frozenset when you need an immutable set that can itself be put inside another set or dict.

All 26 Curriculum Modules