set.add()
Insert a single element into the set. Silently does nothing if the element is already present.
Demo
The demo shows the SET STATE after adding. Python actually returns None; the meaningful effect is mutation. add() silently ignores duplicates — that is the point of sets. In the demo, duplicates in the starting CSV collapse first, then the new element is added (or not, if it's already there). Order shown is not meaningful; Python sets are unordered.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| elem | hashable | yes | The element to add. Must be hashable — ints, floats, strings, tuples of hashables, frozensets are all fine. Lists, dicts, sets raise TypeError. |
Return value
None — Returns None — the useful effect is mutation. The demo shows the set state after adding.
Common patterns
seen = set() for item in items: seen.add(item)
visited = set() queue = [start] while queue: node = queue.pop() if node not in visited: visited.add(node) queue.extend(node.neighbors)
seen.add(x) # no branch; safe to call whether x is there or not
Examples
Pitfalls
s = set() s.add([1, 2])
s.add((1, 2))
s = {1, 2} s = s.add(3) print(s)
s.add(3) # mutate, keep name
count = 0 for x in items: s.add(x) count += 1
count = 0 for x in items: if x not in s: s.add(x) count += 1
s = {1, 2} s.add([3, 4])
s.update([3, 4])
When to use
- Building a set incrementally from a loop or stream
- Tracking visited / seen items in traversals
- De-duplicating items as you encounter them
- "Add if new" without branching — idempotent by design
- Adding many items at once → update() or the `|=` operator
- Elements that are lists / dicts / sets → not hashable
- You need to know whether the element was actually new → check membership first
- Building a NEW set from an existing one → union() or the `|` operator
Notes
FAQ
add() takes ONE element and inserts it into the set. update() takes an ITERABLE and inserts each of its items. Reaching for add() with a list will try to store the list itself — which fails because lists are unhashable.