Python · Hash set · container

set

Python's built-in hash set of unique hashable elements with average O(1) membership and operators for set algebra.

# built in: no import (frozenset is the immutable variant)
class set(iterable=(), /)

CPython 3.14

Operations

OperationTimeWorst caseChanges the collection
addO(1)O(n)Yes
elem in sO(1)O(n)No
remove / discardO(1)O(n)Yes
Set operators | & - ^O(len(s) + len(t)) for union; O(min(len(s), len(t))) for intersection; O(len(s)) for difference—Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
In CPython, an open-addressing hash table with linear probing over small groups of slots, then a perturbed jump.
Ordering
Unspecified (unlike dict, sets do not keep insertion order).
Duplicates
Not stored.
Mutability
Mutable; frozenset is immutable and hashable, so it can be a dict key or a set element.
Memory and ownership
Elements must be hashable.
Equality and comparison
Hash, then identity or ==. There is no custom-comparer parameter: normalise elements (e.g. lower-case strings) before adding.

Pitfalls

  • {} is an empty dict, not an empty set: write set().
  • remove raises KeyError for a missing element; discard does not.
  • Iteration order can differ between runs for strings (hash randomization).

Alternatives

  • frozenset for an immutable set
  • dict.fromkeys(items) to deduplicate while keeping order
  • collections.Counter for a multiset

In other languages

References