Add Items
Existing set items are fixed, but the set can still take on new ones.
The add() method puts a single item into a set.
Example
Put one more item into a set with add():
Prompt
Create a set with "apple", "banana", and "cherry".
Add the item "orange" to the set using the add() method and print the set.
Output: complete Python program
main.py
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Add Sets
The update() method copies the items of another set into the current one.
Example
Copy everything from tropical into thisset:
Prompt
Create two sets: one with "apple", "banana", "cherry" and another with "pineapple", "mango", "papaya".
Use the update() method to add elements from the second set into the first, then print it.
Output: complete Python program
main.py
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Add Any Iterable
update() is not limited to sets. You can hand it any iterable object, such as a tuple, list or dictionary.
Example
Bring the items of a list into a set:
Prompt
Create a set with "apple", "banana", "cherry" and a list with "kiwi", "orange".
Use the update() method to add the list elements to the set and print the result.
Output: complete Python program
main.py
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)