Add Set Items

Sets in Python are mutable, which means you can add new elements after the set is created. However, sets only store unique values, so duplicates are ignored automatically.
This topic covers all valid ways to add items to a set, along with important rules and edge cases.

Add One Item Using add()

The add() method adds a single element to the set.

Syntax

python
set.add(element)

Example

python
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)
Adding a duplicate:
python
fruits.add("apple")
print(fruits)
The set remains unchanged.

Add Multiple Items Using update()

The update() method adds multiple elements from an iterable.

Syntax

python
set.update(iterable)

Example with List

python
fruits = {"apple", "banana"}
fruits.update(["orange", "mango"])
print(fruits)

Example with Tuple

python
numbers = {1, 2}
numbers.update((3, 4, 5))
print(numbers)

Example with Another Set

python
a = {1, 2}
b = {3, 4}

a.update(b)
print(a)

Add Characters from String (Important)

python
letters = set()
letters.update("Python")
print(letters)
Each character is added separately.

Add Items Conditionally

python
numbers = {1, 2, 3}

if 4 not in numbers:
    numbers.add(4)

print(numbers)

Add Items Using Loop

python
numbers = set()

for i in range(5):
    numbers.add(i)

print(numbers)

Add Items to Frozen Set (Not Allowed)

Frozen sets are immutable.
python
fs = frozenset([1, 2, 3])
# fs.add(4)   # AttributeError

Common Mistakes

Using append() on a Set

python
# my_set.append(10)   # AttributeError
Sets do not support append().

Adding Mutable Items

python
# s = set()
# s.add([1, 2])   # TypeError
Only hashable items are allowed.

Important Rules

  • Duplicate values are ignored
  • Order is not preserved
  • Only immutable items can be added
  • add() → single item
  • update() → multiple items

Summary

  • Sets allow adding new items
  • add() adds one element
  • update() adds multiple elements
  • Duplicates are ignored automatically
  • Mutable items cannot be added
  • Frozen sets cannot be modified