set.add()
Puts one element into a set. If the element is already there, nothing happens: a set never holds duplicates.
set.add(elem)add() puts a single element into a set. Because a set keeps only one copy of each value, adding something that is already there changes nothing and raises no error.
That makes add() perfect for remembering what you have already seen: visited pages, unique visitors, words already used.
Two things to know. Sets have no order, so the new element is not "at the end"; and sets of strings may print in a different order each time you run the program, which is why the examples here print sorted(...). Also, only unchangeable values can go into a set: numbers, strings and tuples are fine, but a list raises TypeError.
Parameters
| Parameter | What it is |
|---|---|
elemrequired | The element to add. It must be hashable (unchangeable), such as a number, string or tuple. |
Return value
Nothing (None). The set is changed in place.
Examples
1Add elements, duplicates are ignored
seen = {1, 2}
seen.add(3)
seen.add(2)
print(seen)
print(len(seen)){1, 2, 3}
32Collect unique visitors
A set of strings has no fixed print order, so sort it before printing.
log = ["ana", "ben", "ana", "chloe", "ben"]
visitors = set()
for name in log:
visitors.add(name)
print(len(visitors), "unique visitors")
print(sorted(visitors))3 unique visitors ['ana', 'ben', 'chloe']
3Spot the first repeated value
rolls = [4, 2, 6, 2, 5]
seen = set()
for r in rolls:
if r in seen:
print("First repeat:", r)
break
seen.add(r)First repeat: 2
4Tuples can be elements, lists cannot
cells = set()
cells.add((0, 1))
cells.add((0, 1))
print(len(cells))
try:
cells.add([2, 3])
except TypeError:
print("TypeError: a list cannot go into a set")1 TypeError: a list cannot go into a set
Common mistakes
Using add() for several elements
add() takes one element. Passing a list fails, and passing a string adds the whole string as one element. Use set.update() to add many.
tags = {1}
tags.update([2, 3])
print(tags)
words = set()
words.add("hi")
print(len(words)){1, 2, 3}
1Writing {} for an empty set
{} is an empty dictionary, which has no add(). Write set() for an empty set.
a = {}
b = set()
print(type(a).__name__, type(b).__name__)dict set
Questions people ask
What is the difference between add() and update() for sets?
add(x) adds one element. set.update() takes an iterable and adds each of its elements.
Why does my set print in a different order?
Sets are not ordered. Strings get a new hash on each run, so their print order can change between runs. Print sorted(s) for a stable result.
Does add() tell me if the element was new?
No, it returns None. Check x in s before adding, or compare len(s) before and after.