Sets
A set is an unordered collection of unique, hashable values. It answers "is this in here?" in roughly constant time and silently drops duplicates on insertion.
Detailed Explanation
A set is a hash table with keys and no values. When you add an element, Python hashes it and stores it in a slot derived from that hash. Membership testing repeats the same arithmetic and goes straight to the slot, so email in seen costs about the same whether seen holds ten addresses or ten million. On a list the same test is a linear scan.
That difference decides the shape of real programs. You are de-duplicating email addresses from three exported CSV files. With a list, each if address not in seen scans everything you have collected so far, and processing n addresses costs O(n²). With a set, each check is O(1) on average and the whole job is O(n). At a hundred addresses nobody notices. At two hundred thousand, one version finishes instantly and the other appears to hang.
Sets also give you set algebra directly. If paying and active are sets of user IDs, paying & active is the paying users who are active, paying - active is the churn risk list, and paying ^ active is everyone in exactly one group. Written with loops this is several nested blocks; written with operators it is one line that says what it means.
Two constraints follow from the hash table. First, elements must be hashable, so you can put strings, numbers, tuples, and frozensets in a set, but not lists, dicts, or other sets. Second, a set has no order. Unlike dicts, sets carry no insertion-order guarantee, and the iteration order you observe can change between runs because string hashing is randomised per process. Never let output ordering depend on set iteration; call sorted() when order matters.
| Operation | Average | Worst case | Why |
|---|---|---|---|
x in s, s.add(x), s.discard(x) | O(1) | O(n) | One hash and a short probe; worst case is total collision |
len(s) | O(1) | O(1) | Count is stored |
| iteration | O(n) | O(n) | Walks the table, including empty slots |
a | b (union) | O(len(a) + len(b)) | — | Every element of both must be inserted |
a & b (intersection) | O(min(len(a), len(b))) | O(len(a) × len(b)) | Iterates the smaller set, probes the larger |
a - b (difference) | O(len(a)) | — | Probes b once per element of a |
a <= b (subset) | O(len(a)) | — | Probes b once per element of a |
s.pop() | O(1) | — | Removes an arbitrary element, not the first |
The worst cases assume pathological hashing. In ordinary code, and for built-in types, treat set operations as constant time. A custom class with a constant __hash__ will genuinely degrade a set to a linear scan.
Sets are mutable, which means they are not hashable and cannot be members of other sets or keys in a dict. When you need a set-like value in either position, use frozenset. One syntax trap: {} is an empty dict. The empty set has no literal and must be written set().
The cost of a set is memory and the loss of both order and duplicates. If you need to know how many times each item appeared, you want a Counter. If you need order and duplicates, you want a list.
Code Examples
# De-duplicating addresses: O(n) with a set, O(n^2) with a list.
raw_addresses = ["ana@x.com", "bo@y.com", "ana@x.com", "cy@z.com", "bo@y.com"]
unique_addresses = set(raw_addresses)
print(len(unique_addresses)) # 3
print(sorted(unique_addresses)) # ['ana@x.com', 'bo@y.com', 'cy@z.com']
# set() loses order. To dedupe AND keep first-seen order, use a dict.
ordered_unique = list(dict.fromkeys(raw_addresses))
print(ordered_unique) # ['ana@x.com', 'bo@y.com', 'cy@z.com']
# Building a set incrementally: add() is a no-op on a duplicate.
seen = set()
for address in raw_addresses:
if address in seen: # O(1) average, not a scan
continue
seen.add(address)
print(len(seen)) # 3# Set algebra replaces nested loops with one readable expression.
paying = {"u1", "u2", "u3", "u4"}
active = {"u3", "u4", "u5"}
print(sorted(paying & active)) # ['u3', 'u4'] <- paying and active
print(sorted(paying - active)) # ['u1', 'u2'] <- paying but gone quiet
print(sorted(paying | active)) # ['u1', 'u2', 'u3', 'u4', 'u5']
print(sorted(paying ^ active)) # ['u1', 'u2', 'u5'] <- in exactly one set
print({"u3"} <= paying) # True <- subset test
# The empty set has no literal: {} is a dict.
print(type({}), type(set())) # <class 'dict'> <class 'set'>
# Members must be hashable, so lists cannot go in a set.
try:
{["a", "b"]}
except TypeError as exc:
print(exc) # unhashable type: 'list'Common Gotchas
`{}` is an empty dict, not an empty set
`tags = {}` followed by `tags.add("x")` raises `AttributeError`. Write `tags = set()`.
Sets have no order guarantee
unlike dicts, they make no promise about iteration order, and for string elements it varies between processes because of hash randomisation. Wrap iteration in `sorted()` before printing, comparing text output, or writing files.
`add` versus `update`
`s.add("abc")` inserts one string, while `s.update("abc")` inserts three characters, because `update` iterates its argument. Passing a string to `update` by mistake is a common bug.
Sets discard duplicates and counts
`len(set(words))` tells you how many distinct words exist, never how often each appeared. Use `collections.Counter` when frequency matters.