3.0 Python: Add Set Items
3.1 Add Items
note
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add()
method.
3.1.1 Example
Add an item to a set, using the add()
method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
3.2 Add Sets
To add items from another set into the current set, use the update()
method.
3.2.1 Example
Add elements from tropical
into thisset
:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
3.3 Add Any Iterable
The object in the update() method does not have to be a set, it can be any iterable object (tuples
, lists
, dictionaries
etc.).
3.3.1 Example
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)