In Python, you can add elements to a set using the add()
and update()
methods.
Adding a Single Element with add()
The add()
method adds a single element to the set. If the element is already in the set, it won’t be added again, as sets only contain unique items.
data_set = {1, 2, 3, 4, 5}
data_set.add(6) # Adds 6 to the set
print(data_set) # Output: {1, 2, 3, 4, 5, 6}
data_set.add(2) # Adding a duplicate value; nothing changes
print(data_set) # Output: {1, 2, 3, 4, 5, 6}
Example2:
# Initialize a set
fruits = {"apple", "banana"}
# Add a single element
fruits.add("orange")
print(fruits) # Output: {"apple", "banana", "orange"}
Adding Multiple Elements with update()
To add multiple elements at once, use the update()
method. You can pass any iterable (like a list, tuple, or another set), and all unique items from that iterable will be added to the set.
data_set = {1, 2, 3, 4, 5}
data_set.update([6, 7, 8]) # Adds 6, 7, and 8 to the set
print(data_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
# Adding elements from another set
data_set.update({7, 8, 9})
print(data_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
# Adding elements from a string (unique characters will be added)
my_set.update("hello")
print(data_set) # Output may include {1, 2, 3, 4, 5, 6, 7, 8, 9, 'h', 'e', 'l', 'o'}
Example2:
# Initialize a set
fruits = {"apple", "banana"}
# Add multiple elements
fruits.update(["mango", "orange"])
print(fruits) # Output: {"apple", "banana", "mango", "orange"}