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.
Add an item to a set, using the add()
method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Try it Yourself »
To add items from another set into the current set, use the update()
method.
Add elements from tropical
into thisset
:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Try it Yourself »
The object in the update()
method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!