set.add()
Python · Sets
Theory
.add(item) puts one item into a set, in place, and returns None. If an equal item is already there, nothing happens: no error and no duplicate, which is exactly what makes sets useful for collecting unique values. With cities = {'Mumbai', 'Delhi'}, cities.add('Pune') leaves three cities, and calling cities.add('Pune') again changes nothing.
Under the hood add() hashes the item to find its slot, so it runs in O(1) on average. The item must be hashable: adding a tuple works, but adding a list raises TypeError: unhashable type: 'list'. add() takes exactly one item; to add several at once use update(), which accepts any iterable. Be careful with strings: s.add('Pune') adds one string, while s.update('Pune') adds the letters 'P', 'u', 'n', 'e' separately. Because sets are unordered, the printed position of a new item can vary.
Why we use it
When collecting distinct values in a loop, such as unique customers seen today, add() lets you insert every value without first checking whether it is already there.
When to use it
Use add() for one item at a time inside loops. Use update() to add many items from a list or another set. If you need to keep insertion order or count repeats, use a list, a dict or collections.Counter instead.
How it works
- Call ids.add(104)
- Compute hash(104) to find its slot
- Is an equal item already stored? Yes: Do nothing (no duplicate, no error). No: Store the item.
- Return None
- The set now holds every distinct value once
Syntax
set.add(item)Example
cities = {'Mumbai', 'Delhi'}
cities.add('Pune')
print(cities)Key points
- Adding a value that already exists does nothing (no error, no duplicate)
- Sets have no guaranteed order, so printed order can vary
- Items must be hashable: add((1, 2)) works, add([1, 2]) fails
- Use update() to add several items at once
- update('Pune') adds letters; add('Pune') adds the word