Skip to content
Tutorials Center
My learning

Topics

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().

Python
seen = {1, 2}
seen.add(3)   # {1, 2, 3}

Try it

Python Adding elements

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.

Python Detecting duplicates and unhashable values

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

Python
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 no add().
  • Duplicates are ignored silently. Two elements are the same if they hash equally and compare equal, so 1, 1.0 and True count as one element.
  • Only hashable elements. Store a tuple instead of a list, or a frozenset instead of a set.
  • Check-then-add pattern. x in s followed by s.add(x) is fine; to know whether add() changed anything compare len(s) before and after.
  • One element at a time. s.add("abc") adds the whole string, not its letters. Use set.update() to add each item of an iterable.
  • Average cost is constant time, regardless of the set's size.