Skip to main content

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

s = {1, 2, 3}
s.add(4)
s.remove(2)
print(s)
Common methods:
  • add(x)
  • remove(x)
  • discard(x)
  • pop()
  • clear()

Set operations

a = {1, 2, 3}
b = {3, 4, 5}

print(a | b)  # union
print(a & b)  # intersection
print(a - b)  # difference
print(a ^ b)  # symmetric difference

remove vs discard

s = {1, 2, 3}
# s.remove(9)   # KeyError
s.discard(9)    # no error

Subset and superset checks

a = {1, 2}
b = {1, 2, 3}
print(a <= b)  # True
print(b >= a)  # True

Trap: list inside set

# s = {[1, 2], [3, 4]}  # TypeError
Reason:
  • 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 discard if uncertain whether element exists

Quick practice

  1. Find common elements of {1, 2, 3} and {2, 3, 4}.
  2. Remove duplicates from [5, 5, 6, 7, 7].
  3. Explain why sets do not support indexing.

Answer key

  1. {2, 3}
  2. set([5, 5, 6, 7, 7])