add-remove
set.add
Adds a single hashable element to the set in place. If the element is already present, the set is unchanged (no error).
s.add(elem) Parameters
| Parameter | Purpose |
|---|---|
| elem | The hashable element to insert (str, int, tuple, frozenset, etc.) |
| returns | None — the set is mutated in place |
Examples
>>> s = {1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4} Adds a new element.
>>> s = {1, 2, 3}
>>> s.add(2)
>>> s
{1, 2, 3} Adding an existing element is a no-op.
>>> s = set()
>>> s.add((1, 2))
>>> s
{(1, 2)} Tuples are hashable and allowed as elements.
>>> s = set()
>>> s.add([1, 2])
TypeError: unhashable type: 'list' Lists are unhashable — cannot be set elements.
Gotcha
add takes exactly ONE element, not multiple — use update() for many. The element must be hashable, so lists, dicts, and sets cannot be added (use a tuple or frozenset instead).
Related methods
set.update
Adds every element from each iterable argument to s in place. Equivalent to a union but mutates s instead of returning a new set.
set.discard
Removes an element from the set if it is present, and does nothing otherwise. Unlike remove(), never raises an error.
set.remove
Removes the specified element from the set. Raises KeyError if the element is not present.
set.pop
Removes and returns an arbitrary element from the set. Raises KeyError if the set is empty.
set.clear
Removes all elements from the set, leaving it empty. Mutates the set in place; other references to the same set see it emptied.
← All Python set methods · List methods · list vs tuple vs set