Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python Add Set Items


Add Set Items

You cannot change the items in a set, but you can add new ones.

Use the add() function to add a new item to the set.

Example
colors_set = {"Red", "Blue", "Green"}
colors_set.add("Purple")
print(colors_set)
{'Blue', 'Red', 'Green', 'Purple'}

In the above example, we have added the color "Purple" to a set using the add() function.


Use the update() function to add a new set to the current set.

Example
colors_set = {"Red", "Blue", "Green"}
new_colors_set = {"Purple", "Grey"}

colors_set.update(new_colors_set)

print(colors_set)
{'Blue', 'Green', 'Purple', 'Red', 'Grey'}

In the above example, we created two different sets, and then we used the update() function to add a new_colors_set to colors_set. Here, you can see that when we print colors_set, all items from the new_colors_set are added to colors_set.


Using the update() function, you can add an iterable object to the set, such as a list, tuple, or dictionary.

Example
colors_set = {"Red", "Blue", "Green"}
colors_list = ["Purple", "Grey"]

colors_set.update(colors_list)

print(colors_set)
{'Purple', 'Grey', 'Blue', 'Green', 'Red'}

In the above example, using the update() function, we are adding a Python list to the current set.


Example
colors_set = {"Red", "Blue", "Green"}
colors_tuple = ("Purple", "Grey")

colors_set.update(colors_tuple)

print(colors_set)
{'Red', 'Grey', 'Green', 'Blue', 'Purple'}

In the above example, using the update() function, we are adding a Python tuple to the current set.