可以使用内置add()
函数将元素添加到Set中。通过使用add()
方法一次只能将一个元素添加到集合中,循环用于使用方法一次添加多个元素,add()
而对于添加两个或更多元素Update()
,使用方法。该update()
方法接受列表,字符串,元组以及其他集作为其参数。在所有这些情况下,避免了重复的元素。
注 -列表不能作为元素添加到集合中,因为列表不可清除,而可以添加元组,因为元组是不可变的,因此可以Hashable。
# Python program to demonstrate
# Addition of elements in a Set
# Creating a Set
set1 = set()
print("Intial blank Set: ")
print(set1)
# Adding element to the Set
set1.add(8)
set1.add(9)
set1.add(12)
print("\nSet after Addition of Three elements: ")
print(set1)
# Adding elements to the Set
# using Iterator
for i in range(1, 6):
set1.add(i)
print("\nSet after Addition of elements from 1-5: ")
print(set1)
# Adding Tuples to the Set
set1.add((6,7))
print("\nSet after Addition of a Tuple: ")
print(set1)
# Addition of elements to the Set
# using Update function
set1.update([10, 11])
print("\nSet after Addition of elements using Update: ")
print(set1)








暂无数据