Adds a single item to a set
Usage
The add()
method adds a single item to a set. This method does not return anything; it updates the set in place.
Syntax
set.add(item)
Parameter | Condition | Description |
item | Required | An item you want to add to a set |
Examples
# Add a single item 'yellow' to a set
S = {'red', 'green', 'blue'}
S.add('yellow')
print(S)
# Prints {'blue', 'green', 'yellow', 'red'}
If you try to add an item that already exists in the set, the method does nothing.
S = {'red', 'green', 'blue'}
S.add('red')
print(S)
# Prints {'blue', 'green', 'red'}
The item you want to add must be of immutable (unchangeable) type.
# A tuple can be added in a set
S = {'red', 'green', 'blue'}
S.add((1, 2))
print(S)
# Prints {'blue', (1, 2), 'green', 'red'}
# But list can’t be a set item
S = {'red', 'green', 'blue'}
S.add([1, 2])
# Triggers TypeError: unhashable type: 'list'