Sets
Set Methods
add, remove, discard, pop
Interview: Tests understanding of set mutation methods and error handling
Sets provide methods for adding, removing, and updating elements. A key distinction is between safe removal (discard()) and strict removal (remove()). In-place update operators (|=, &=, -=, ^=) modify the set without creating a new one.
Adding Elements
- add(elem): Add single element — O(1). No effect if already present
- update(*iterables): Add all elements from one or more iterables — same as
|=
Removing Elements
- remove(elem): Remove element — raises KeyError if not found
- discard(elem): Remove element — no error if not found (safer)
- pop(): Remove and return an arbitrary element — raises KeyError if empty. Note: NOT LIFO/FIFO
- clear(): Remove all elements
In-place Update Operators
- |= (update): Add all elements from another set
- &= (intersection_update): Keep only common elements
- -= (difference_update): Remove elements found in another set
- ^= (symmetric_difference_update): Keep elements in one but not both
Use Cases
Building unique collections from multiple data sources
Filtering data to valid/allowed values
Incremental set operations in algorithms
Processing pipelines that accumulate or narrow data
Common Mistakes
Using remove() without checking membership first (KeyError) — prefer discard()
Thinking pop() returns the "first" or "last" element — it returns an arbitrary element
Using | (operator) instead of update() when the right operand is not a set
Forgetting that in-place operators (|=, &=) modify the original set