How to add elements to a set in Python?

In Python, sets are containers with unique and unordered elements. You can add elements to a set using the add() method or the update() method.

Add a single element using the add() method.

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # 输出: {1, 2, 3, 4}

Add multiple elements using the update() method.

my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set)  # 输出: {1, 2, 3, 4, 5, 6}

You can add element types such as numbers, strings, tuples, etc., which are immutable. Mutable types like lists and dictionaries cannot be added.

bannerAds