set · Python

add

Adds an element; does nothing if it is already present.

set.add(elem, /)

Complexity

AverageO(1)
AmortizedO(1)
Worst caseO(n)
Extra spaceO(1) amortized

Assumes: Good hash distribution.

Hash and probe for a free or equal slot.

Tested example

seen: set[int] = set()  # {} would be an empty dict
seen.add(4)
seen.add(4)  # already present: no change, no error, no return value
assert seen == {4}
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_set.py

Parameters

elem
A hashable element.

Behaviour

Returns
None (it does not tell you whether the element was new: test `in` first if you need to know).
Errors and preconditions
TypeError for an unhashable element.
Changes
At most one new element; may resize.
Memory and invalidation
May resize. Changing the size during iteration raises RuntimeError.