Skip to main content
Albero Academy

Sets

Unordered collections of unique values, with fast membership and set algebra.

Data Structures9 min

A set is an unordered collection of unique values. It automatically drops duplicates, tests membership extremely fast, and supports the mathematical set operations — union, intersection, difference. Reach for it whenever uniqueness or fast "is it in here?" matters.

Creating sets

uniqueness is automatic
s = {1, 2, 2, 3} # {1, 2, 3} — the duplicate 2 is dropped
s.add(4) # {1, 2, 3, 4}
s.discard(1) # remove 1 (no error if absent)
empty = set() # NB: {} is an empty DICT, not a set!

Fast membership

Checking x in s on a set is near-instant (O(1) on average) regardless of size — far faster than scanning a list. If you repeatedly test membership, a set is the right tool:

de-duplicate & test
seen = set()
for item in stream:
if item in seen: # O(1) check
continue
seen.add(item)
unique = set([1, 1, 2, 3]) # {1, 2, 3} — de-duplicate a list
count = len(set(words)) # number of distinct words

Set algebra

OperatorMeaning
a & bIntersection — in both
a | bUnion — in either
a - bDifference — in a, not b
a ^ bSymmetric difference — in one, not both
combining sets
a = {1, 2, 3}
b = {2, 3, 4}
a & b # {2, 3}
a | b # {1, 2, 3, 4}
a - b # {1}
a ^ b # {1, 4}

Key takeaways

  1. 01Sets store unique values and are unordered — duplicates are dropped automatically.
  2. 02Membership testing (x in s) is very fast — O(1) average.
  3. 03Set algebra: & intersection, | union, - difference, ^ symmetric difference.
  4. 04set(list) is the idiomatic way to de-duplicate.
  5. 05Beware: {} is an empty dict — use set() for an empty set.

Finished this chapter?

Mark it complete to track your progress through Python.