Skip to main content

Python Sets

Satellite · Data Types

Python Sets

Sets track unique elements and support fast membership checks. Use them for deduplication, tagging, and math-like operations.

Creation

items = {1, 2, 3}
empty = set()
deduped = set(["a", "b", "a"])

Operations

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

Membership checks are O(1) on average: if email in unsubscribed: ...

Frozenset

Immutable set; use when you need to store sets inside other sets or as dict keys.

Next up in your learning path