GGistDev

Sets in Python

Sets are unordered collections of unique, hashable elements with fast membership tests and rich set operations.

Creating sets

Use curly braces for non-empty sets; set() for an empty set (since {} is a dict).

nums = {1, 2, 3}
empty = set()
chars = set("hello")   # {'h','e','l','o'}

Keys must be hashable (immutable). Use frozenset for an immutable set or when you need to put a set inside another set/dict key.

fs = frozenset({1, 2})

Adding and removing

Add single or many items; remove with or without raising on missing.

s = {1, 2}
s.add(3)
s.update([3, 4, 5])   # add many
s.remove(5)           # KeyError if 5 not present
s.discard(42)         # no error if absent
s.pop()               # remove and return an arbitrary element
s.clear()             # empty the set

Set operations (mathematical)

Use operators or methods; operators are concise and preferred.

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

u = a | b              # union {1,2,3,4}
i = a & b              # intersection {3}
d = a - b              # difference {1,2}
x = a ^ b              # symmetric difference {1,2,4}

subset  = {1,2} <= a   # True
proper  = {1,2} < a    # True

In-place updates are available: a |= b, a &= b, a -= b, a ^= b.

Membership and iteration

Membership is average O(1).

2 in a   # True
for v in a:
    ...   # order is arbitrary

Comprehensions

Build sets succinctly with a comprehension.

squares = {n*n for n in range(6)}

Pitfalls and tips

  • Unhashable elements (e.g., lists, dicts) cannot be added; convert to tuple or use frozenset
  • Set iteration order is insertion-preserving as of CPython 3.7+, but treat it as arbitrary in logic
  • Prefer sets for deduplication and fast in checks over lists

Summary

  • Sets store unique, hashable elements; support efficient union/intersection/difference
  • Use discard for safe deletes; use frozenset when immutability or nesting is required