Python 3 reference · Set Methods
Python Set add() Method
Add one element to the set. Adding an element that is already present does nothing.
Python 3 Since 3.0
Syntax
set.add(elem)
Parameters
| Parameter | Description |
|---|---|
elem |
A hashable value. |
Return value
None.
Examples
seen = {"a"}
seen.add("b")
seen.add("a")
print(sorted(seen))
Output
['a', 'b']
visited = set()
for page in ["home", "about", "home"]:
if page in visited:
print("already saw", page)
visited.add(page)
Output
already saw home
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
set.update()· Add all elements from one or more iterables to the set, in place. The same as a |= b.set.discard()· Remove an element if it is present; do nothing if it isn't. The no-error version of remove().set.remove()· Remove an element from the set. Raises KeyError if it isn't present; use discard() to avoid the error.- Python Sets · tutorial