Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.update() method

Reference for Python set.update(): add all elements of one or more iterables to a set in place, the |= operator, strings as iterables and the None return value.

The update() method adds every element from one or more iterables to a set, in place. Elements that are already present are ignored, because a set holds each value only once.

It is the in-place counterpart of union(), and s |= other does the same for sets. Compare it with add(), which adds exactly one element.

Python
tags = {"a"}
tags.update(["b", "c"], {"d"})

Try it

Python Adding many 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 update() versus add(), and string surprises

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.update(*others)
set |= other
Name Description
*others Zero or more iterables whose items are added. Items must be hashable.

Return value: None.

Raises: TypeError if an argument is not iterable or contains unhashable items (a list inside a list, for example).

Usage notes

  • Mutates and returns None. Writing s = s.update(x) throws your set away.
  • Strings are iterables. s.update("dog") adds "d", "o" and "g". To add a whole string, use s.add("dog") or s.update(["dog"]).
  • Dictionaries add their keys, and update() accepts any iterator or generator, which is consumed.
  • The method accepts any iterable; |= requires a set or frozenset.
  • If an unhashable item appears midway, earlier items may already have been added before TypeError is raised.
  • Not the same as dict.update(). A set has no values to overwrite; it only gains new elements.
  • Updating a set with itself changes nothing.
  • Frozensets have no update(); use union() to build a new one.