Add Set Items
Adding Items to Sets
Sets are mutable collections, so new elements can be added after creation.
Use the add() method to insert a single element. If the element is already present, the set remains unchanged.
Use the update() method to add multiple elements from an iterable (such as a list, tuple, set, or string).
# Adding items to sets
fruits = {"apple", "banana", "cherry"}
# Add single item
fruits.add("orange")
print(fruits)
# Add multiple items
fruits.update(["mango", "grape"])
print(fruits)
{'cherry', 'banana', 'apple', 'orange'} {'cherry', 'banana', 'mango', 'apple', 'grape', 'orange'}
Adding Duplicates
Adding an existing element does not change the set, since sets automatically enforce uniqueness.
# Adding duplicate elements
numbers = {1, 2, 3}
numbers.add(2)
print(numbers)
{1, 2, 3}
Using Update with Different Iterables
The update() method accepts one or more iterables. All elements from the iterables are added to the set.
# Update with multiple iterables
colors = {"red", "green"}
colors.update(["blue", "yellow"], {"black", "white"}, ("pink", "purple"))
print(colors)
{'red', 'purple', 'pink', 'yellow', 'green', 'blue', 'black', 'white'}
Adding Characters from a String
Strings are iterables, so using update() with a string adds each character individually to the set.
# Adding characters from a string
letters = {"a", "b"}
letters.update("cat")
print(letters)
{'a', 'b', 't', 'c'}
Best Practices
Use add() when inserting a single element for clarity.
Use update() for merging multiple items at once from iterables.
Be cautious when using update() with strings, since each character is treated as a separate element.
Remember that sets do not allow duplicates, so re-adding an element has no effect.