add-remove
set.update
Adds every element from each iterable argument to s in place. Equivalent to a union but mutates s instead of returning a new set.
s.update(*others) | s |= other Parameters
| Parameter | Purpose |
|---|---|
| *others | Any number of iterables (method) or sets (|= operator) |
| returns | None from the method; |= rebinds s |
Examples
>>> s = {1, 2}
>>> s.update([3, 4], {4, 5})
>>> s
{1, 2, 3, 4, 5} Merges multiple iterables into s.
>>> s = {1}
>>> s |= {2, 3}
>>> s
{1, 2, 3} |= augmented assignment (both operands must be sets).
>>> s = set()
>>> s.update('abc')
>>> s == {'a', 'b', 'c'}
True Strings iterate as characters.
>>> s = {1, 2}
>>> s.update()
>>> s
{1, 2} No arguments is a valid no-op.
Gotcha
update() takes iterables, not single elements — s.update(5) fails because 5 is not iterable; use s.add(5). Strings iterate character-by-character.
Related methods
set.add
Adds a single hashable element to the set in place. If the element is already present, the set is unchanged (no error).
set.union
Returns a NEW set containing every element that appears in s or any of the arguments. The method accepts any iterable(s); the | operator requires all operands to be sets or frozensets.
set.intersection_update
Updates s in place, keeping only elements found in s AND every given iterable. The method form accepts iterables; &= requires sets.
set.remove
Removes the specified element from the set. Raises KeyError if the element is not present.
set.discard
Removes an element from the set if it is present, and does nothing otherwise. Unlike remove(), never raises an error.
← All Python set methods · List methods · list vs tuple vs set