set · Python
add
Adds an element; does nothing if it is already present.
set.add(elem, /)
Complexity
| Average | O(1) |
|---|---|
| Amortized | O(1) |
| Worst case | O(n) |
| Extra space | O(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}
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.