Python theorytheory 0/50 · 0%
Collections · easy

8. Sets

Unordered collections of unique, hashable items.

Sets store unique, hashable elements with no guaranteed order, and support fast membership tests and mathematical set operations.

python
seen = {"0xabc", "0xdef"}
seen.add("0x123")
"0xabc" in seen             # O(1) average

a = {1, 2, 3}
b = {2, 3, 4}
a & b   # intersection {2, 3}
a | b   # union {1, 2, 3, 4}
a - b   # difference {1}

Sets are commonly used to deduplicate a list: `unique = list(set(addresses))` (note this loses original order).

Check your understanding

  1. 1. What is the time complexity of membership testing in a set?

  2. 2. What does `a & b` compute for sets?

  3. 3. What must set elements be?