Python Reference ยท Dictionaries and Sets
Python set.add() method
Reference for Python set.add(): insert one element into a set in place, what happens with duplicates, the hashability rule and how it differs from update().
The add() method inserts a single element into a set. If an equal element is already there, the set stays as it is; nothing is raised and no duplicate appears. The method works in place and returns None.
Use add() to build up a collection of unique values, such as the distinct words you have seen so far. To add several elements at once, use update().
seen = {1, 2} seen.add(3) # {1, 2, 3}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
set.add(elem)
| Name | Description |
|---|---|
elem |
The element to insert. It must be hashable. |
Return value: None.
Raises: TypeError if elem is unhashable (a list, dict or set, for instance).
Usage notes
- It mutates the set. Frozen sets (
frozenset) have noadd(). - Duplicates are ignored silently. Two elements are the same if they hash equally and compare equal, so
1,1.0andTruecount as one element. - Only hashable elements. Store a tuple instead of a list, or a
frozensetinstead of a set. - Check-then-add pattern.
x in sfollowed bys.add(x)is fine; to know whetheradd()changed anything comparelen(s)before and after. - One element at a time.
s.add("abc")adds the whole string, not its letters. Useset.update()to add each item of an iterable. - Average cost is constant time, regardless of the set's size.
Related
set.update(),set.discard(),set.remove(),set()- Lessons: Sets