ReferenceSet methods

Python Set add() Method

Short answer
set.add(element) inserts one element into a set in place and returns None. If the element is already in the set, nothing changes and no error is raised.

A set keeps each value only once, so add() is the natural way to collect unique items one at a time, such as the distinct tags on a post or the cities customers ordered from. You never have to check for duplicates yourself, because the set does that for you.

If you want to add many values at once, look at set.update() instead. The rest of this page covers what add() accepts, what it returns and the mistakes beginners hit most often.

Quick facts
Syntaxmy_set.add(element)
Parameterselement: one hashable object (number, string, tuple of hashables, ...)
ReturnsNone (the set is changed in place)
Time complexityO(1) on average

How set.add() works

Python computes the hash of the element and stores it in the set's internal table. Because a set cannot hold two equal values, adding something that is already present is silently ignored.

Python
colors = {"red", "green"}
colors.add("blue")
colors.add("red")   # already there, no effect
print(sorted(colors))
print(len(colors))

The order of items in a set is not guaranteed, so the examples print sorted(...) to get stable output.

What you can and cannot add to a set

Only hashable objects can be set elements. Numbers, strings, booleans, None and tuples that contain only hashable values are fine. Lists, dictionaries and other sets are mutable and therefore unhashable, so adding one raises TypeError. Convert a list to a tuple first if you need to store it.

Value you addAllowed?Why
"python"YesStrings are immutable and hashable
42YesNumbers are hashable
(1, 2)YesA tuple of hashables is hashable
[1, 2]No, TypeErrorLists are mutable
{"a": 1}No, TypeErrorDictionaries are mutable
{1, 2}No, TypeErrorSets are mutable (use frozenset)

add() vs update() vs the | operator

add() takes exactly one element. To merge several values, use update() or build a new set with the union operator. Passing a string to update() would add its characters, while add() keeps the string whole.

ToolAddsChanges the set in place?Result for {1} and [2, 3]
add()One elementYes{1, (2, 3)} when given the tuple (2, 3)
update()Every item of the iterablesYes{1, 2, 3}
|Items of another setNo, new set{1, 2, 3}

Examples you can run

Press Run, then edit the code and run it again.

Collect unique cities from orders

Loop over orders and add() each city. Repeated cities are stored once.

Collect unique cities from orders
orders = ["Pune", "Delhi", "Pune", "Mumbai", "Delhi"]
cities = set()
for city in orders:
    cities.add(city)
print(sorted(cities))
print(len(cities))
Expected output['Delhi', 'Mumbai', 'Pune']
3

Adding a tuple versus a string

A tuple is added as one element. Compare with update(), which would unpack it.

Adding a tuple versus a string
points = set()
points.add((2, 3))
points.add((2, 3))
print(points)
print(len(points))
tags = set()
tags.add("sale")
print(tags)
Expected output{(2, 3)}
1
{'sale'}

Common mistakes

Using the return value

✗ Wrong

seen = {1, 2}
seen = seen.add(3)
print(seen)
None

✓ Right

seen = {1, 2}
seen.add(3)
print(sorted(seen))

add() returns None. Call it on its own line and keep using the original set.

Adding a list

✗ Wrong

groups = set()
groups.add([1, 2])
TypeError: unhashable type: 'list'

✓ Right

groups = set()
groups.add(tuple([1, 2]))
print(groups)

Lists cannot be set elements. Convert to a tuple, which is hashable.

Expecting {} to create a set

✗ Wrong

items = {}
items.add(5)
AttributeError: 'dict' object has no attribute 'add'

✓ Right

items = set()
items.add(5)
print(items)

Empty braces make a dictionary. Create an empty set with set().

Python Set add() Method: questions people ask

Does set.add() return anything?

No. It returns None and modifies the set in place, so s = s.add(x) replaces your set with None.

What happens if I add a duplicate to a set?

Nothing happens. The set already contains an equal element, so it stays unchanged and Python raises no error.

How do I add multiple items to a set in Python?

Use set.update() with an iterable, for example s.update([1, 2, 3]). add() always inserts exactly one element.

Keep learning

Step-by-step lessons:
Python SetsPython Set Operations

Related:
Python Set update() MethodPython Set remove() MethodPython Set discard() MethodPython Set union() Method

More in set methods:
Python Set remove() MethodPython Set discard() MethodPython Set pop() MethodPython Set union() MethodPython Set intersection() MethodPython Set difference() MethodPython Set symmetric_difference() MethodPython Set update() Method See all →