Phase 2 · Data StructuresModule 11~26 min read

Sets

Collections of unique elements with fast membership and powerful set algebra.

What you'll learn

A set is an unordered collection of unique elements. Whenever "no duplicates" matters, or you need blazing-fast membership tests, or you want to do set algebra (union, intersection…), a set is the perfect tool.

By the end you'll be able to:

  • Create sets and rely on their uniqueness
  • Add and remove elements
  • Combine sets with union, intersection, and difference
  • Use sets to deduplicate and test membership quickly

Creating sets

A set uses curly braces, like a dictionary, but with single values instead of key-value pairs. Its defining feature: duplicates are automatically removed, and it has no order or indexing:

sets.py
nums = {1, 2, 3, 2, 1}   # duplicates are removed automatically
print(nums)              # {1, 2, 3}
print(len(nums))         # 3

empty = set()            # NOTE: {} makes an empty DICT, not a set!

The empty-set gotcha

{} creates an empty dictionary, not a set! For an empty set you must use set(). (A non-empty set like {1, 2} is fine.)

Adding & removing

Sets are mutable: .add(x) adds an element, .discard(x) removes one safely (no error if absent), and .remove(x) removes it but raises an error if it's not there. One very common use is turning a list into a set to instantly drop duplicates:

dedupe.py
names = ["Sara", "Omar", "Sara", "Aisha", "Omar"]

unique = set(names)        # instantly remove duplicates
print(len(unique))         # 3 unique names
print("Sara" in unique)    # True

Set operations

This is where sets are magical. Borrowing from mathematics, sets support powerful combination operators that would take loops to write by hand:

Set algebra

|

Union

{1,2,3} | {3,4} → {1,2,3,4}

&

Intersection

{1,2,3} & {2,3,4} → {2,3}

-

Difference

{1,2,3} - {2,3} → {1}

^

Symmetric diff

{1,2} ^ {2,3} → {1,3}

operations.py
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)   # union          {1, 2, 3, 4, 5, 6}
print(a & b)   # intersection   {3, 4}
print(a - b)   # difference     {1, 2}
print(a ^ b)   # symmetric diff {1, 2, 5, 6}

Note

These are perfect for real questions: "which users are in both groups?" (intersection), "who's in group A but not B?" (difference), "all unique tags across every post" (union).

Why sets are fast

Like dictionary keys, set elements are hashed, which makes checking membership (x in myset) almost instant — O(1) on average — regardless of size. Testing x in mylist, by contrast, scans the whole list. For large membership checks, a set is dramatically faster:

speed.py
big = set(range(1_000_000))

# checking membership in a set is near-instant (O(1)),
# no matter how large it is — far faster than scanning a list.
print(999_999 in big)   # True

Tip

There's also frozenset — an immutable set. Because it can't change, it's hashable, so it can be a dictionary key or an element of another set.

Recap & quick check

Key takeaways

  • A set is an unordered collection of unique elements — duplicates are dropped automatically.
  • Use set() for an empty set; {} makes an empty dict.
  • Combine sets with | (union), & (intersection), - (difference), ^ (symmetric difference).
  • set(a_list) instantly deduplicates a list.
  • Membership tests (x in myset) are near-instant O(1) — far faster than scanning a list.

Quick check

1. What happens to duplicate values added to a set?

2. How do you create an empty set?

3. Which operator gives the intersection of two sets?

4. Why are membership tests fast in a set?

5. How do you deduplicate a list quickly?

Great — sets round out your collections toolkit. Next up: Module 12 — Comprehensions & Generator Expressions, the finale of Phase 2.