add(item) puts one item into a set. The set is changed in place: no new set is created, and every name that refers to the set sees the new item.
A set keeps each value only once, so adding something that is already there does nothing and raises no error. The item must be hashable: numbers, strings, and tuples of those are fine, but a list, a dict, or another set raises TypeError.
set.add() is an instance method of the built-in set type: call it on a set with dot notation, such as tags.add(...). No import is needed.
Syntax
Pass the single item to add, and call it on its own line, because the return value is always None.
python
s.add(item)
Call
What it does
{1, 2}.add(3)
Returns None; the set becomes {1, 2, 3}.
{1, 2}.add(2)
Returns None; the set becomes {1, 2}, unchanged because 2 is already there.
{1, 2}.add([3])
Raises TypeError: a list is unhashable, so it cannot be a set item.
Adding is fast no matter how large the set is. To add several items at once use update(), or the |= operator with another set.
Method signatures
python
set.add(item)
# returns: None; item is now in the set (no change if it was already there)
# raises: TypeError if item is unhashable
Parameters
Parameter
Description
item
Any hashable object, added as a single element. Exactly one argument is required: add(1, 2) raises TypeError, and so does add([1, 2]).
Return Value
Return Value
Description
None
Always None. The useful result is the set itself, which now contains the item.
Python Examples
Example 1 — Count Unique Visitors on a Website
Add every page hit to a set and see that repeat visitors are stored only once.
python
visitors = set()
for page_hit in ["u17", "u03", "u17", "u42", "u03", "u17"]:
visitors.add(page_hit)
print(len(visitors))
print(sorted(visitors))
print(visitors.add("u99"))
Output
3
['u03', 'u17', 'u42']
None
How It Works
Start empty.set() creates an empty set; writing {} would create an empty dict instead.
Repeats vanish. Six hits are added, but "u17" and "u03" appear several times and are stored once, so the set holds three ids.
Sorted for a stable print. A set has no fixed order, so sorted() turns the visitors into an alphabetical list.
None, even for new ids.add() returns None whether or not the item was new, so "u99" prints None.
Example 2 — Tell New Tags From Existing Ones
Use in to report whether each tag is new, then add only the new ones.
python
tags = {"python", "sets"}
for tag in ["sets", "loops", "python", "loops"]:
if tag in tags:
print(tag, "already exists")
else:
tags.add(tag)
print(tag, "added")
print(len(tags))