Python – Add Set Items
Python sets are mutable, meaning you can add new items to them after creation. You can use the add()
method to add a single item and update()
to add multiple items at once.
Python sets allow dynamic insertion of items. You can add:
- A single item using
add()
- Multiple items using
update()
1. Add a Single Item using add()
languages = {"Python", "Java"}
languages.add("C++")
print(languages)
Output:
{'Python', 'Java', 'C++'}
add()
inserts an item only if it's not already in the set.
2. Adding an Existing Item (No Error, No Effect)
languages = {"Python", "Java"}
languages.add("Python")
print(languages)
Output:
{'Python', 'Java'}
No duplicate is added, and Python doesn’t raise an error.
3. Add Multiple Items using update()
languages = {"Python", "Java"}
languages.update(["C++", "JavaScript"])
print(languages)
Output:
{'Python', 'JavaScript', 'C++', 'Java'}
4. Add Items from Another Set
set1 = {"HTML", "CSS"}
set2 = {"JavaScript", "React"}
set1.update(set2)
print(set1)
Output:
{'JavaScript', 'React', 'HTML', 'CSS'}
5. Add Items from a Tuple
tools = {"Git", "Docker"}
tools.update(("Kubernetes", "Ansible"))
print(tools)
Output:
{'Git', 'Docker', 'Kubernetes', 'Ansible'}
6. Add Characters from a String (Character-by-Character)
alphabets = {"a", "b"}
alphabets.update("cde")
print(alphabets)
Output:
{'e', 'b', 'd', 'c', 'a'}
⚠️ Strings are iterables, so
update("cde")
adds'c'
,'d'
, and'e'
individually.
7. Add Elements from a List of Mixed Data Types
mixed = {1, 2}
mixed.update([3, "four", (5, 6)])
print(mixed)
Output:
{1, 2, 3, 'four', (5, 6)}
Sets can hold mixed types as long as they’re hashable.
8. Add Elements from Another Set Conditionally
a = {1, 2, 3}
b = {3, 4, 5}
# Add only elements > 3 from b
a.update({x for x in b if x > 3})
print(a)
Output:
{1, 2, 3, 4, 5}
You can use set comprehensions with
update()
for more control.
Bonus Tip: Immutable Types Only
You can only add immutable (hashable) items like strings, numbers, and tuples. Trying to add a list will raise an error:
items = {1, 2}
items.add([3, 4]) # ❌ ERROR: list is unhashable
Summary Table
Method | Description | Input Type | Adds |
---|---|---|---|
add(x) | Adds one item | Any hashable type | Single element |
update(iterable) | Adds multiple items | List, tuple, set, etc. | All items from iterable |