Guide Python Beginner

12.4 Adding Elements

add() for a single element that silently no-ops on a duplicate, update() for merging in one or more other iterables at once, and how that maps to list.append() and list.extend().

2 min read

add()

Adds one element — silently does nothing if it’s already present (no error, no duplicate).

>>> s = {1, 2}
>>> s.add(3)
>>> s
{1, 2, 3}

update()

Adds every element from one or more other iterables — the set equivalent of 10.7 List Methods’ list.extend().

>>> s.update([4, 5], {6, 7})
>>> s
{1, 2, 3, 4, 5, 6, 7}

Adding Multiple Elements

update() accepts any number of iterables at once, of any iterable type (list, tuple, another set, …), merging them all in a single call.

Quick Interview Answer

“add() inserts exactly one element and is a silent no-op if it’s already present — there’s no error either way, which is a deliberate consequence of a set never having duplicates to begin with. update() is the multi-element equivalent, roughly mapping to list.extend(): it accepts any number of iterables in a single call and merges every element from each of them in, deduplicating automatically as it goes.”

Common Mistakes

  • Calling s.add([1, 2]) expecting it to add two elements — it tries to add the list [1, 2] as a single element and raises TypeError: unhashable type: 'list'; use update() for that instead.
  • Using add() in a loop to merge in another collection, when a single update() call does the same thing more directly.
  • Expecting add() on an existing value to raise an error or count occurrences — it’s always a silent no-op, since a set has no concept of duplicate membership.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form