Learning outcomes
By the end of this lecture, you should be able to:- use set methods confidently
- apply union, intersection, and difference
- explain why sets are useful in duplicate removal and membership
Set methods
add(x)remove(x)discard(x)pop()clear()
Set operations
remove vs discard
Subset and superset checks
Trap: list inside set
- lists are mutable, so they cannot be set elements
Exam hints and traps
pop()removes arbitrary element from set- order-based answers are unsafe for sets
- use
discardif uncertain whether element exists
Quick practice
- Find common elements of
{1, 2, 3}and{2, 3, 4}. - Remove duplicates from
[5, 5, 6, 7, 7]. - Explain why sets do not support indexing.
Answer key
{2, 3}set([5, 5, 6, 7, 7])
