Python Set add() Method

Adds a single item to a set

Usage

The add() method adds a single item to a set.

The method does not return anything; it just updates the set.

Syntax

set.add(item)

Python set add() method parameters
ParameterConditionDescription
itemRequiredAn item you want to add to a set

Examples

Example: Add a single item ‘yellow’ to a set

S = {'red', 'green', 'blue'}
S.add('yellow')
print(S)    # {'blue', 'green', 'yellow', 'red'}

If you try to add an item that already exists in the set, the method does nothing.

Example: Try to add a duplicate item ‘red’

S = {'red', 'green', 'blue'}
S.add('red')
print(S)    # {'blue', 'green', 'red'}

The item you want to add must be of immutable (unchangeable) type.

Example: A tuple can be added in a set

S = {'red', 'green', 'blue'}
S.add((1, 2))
print(S)    # {'blue', (1, 2), 'green', 'red'}

But list can’t be a set item

# TypeError: unhashable type: 'list'
S = {'red', 'green', 'blue'}
S.add([1, 2])