How to Add Element to a Set in Python

To add elements to a set in Python, you can use different methods.

The following examples show how to add an element to a set using different methods in Python.

Using add() Function

We can use the add() function to add a single element to a set.

Suppose we have the following set:

# Create a set
my_set = {"apple", "banana", "cherry"}

# Add a single element to the set
my_set.add("orange")

# Show set
print("Updated set after adding single element:", my_set)

Output: 👇️

Updated set after adding single element: {'banana', 'orange', 'cherry', 'apple'}

In this example, we use the add() function to add the element orange to the set.

Using update() Function

We can use the update() function to add a single element to a set.

Suppose we have the same set as above.

We can use the following code to add the element mango to the set:

# Add a single element to the set
my_set.update(["mango"])

# Show set
print("Updated set after adding single element:", my_set)

Output: 👇️

Updated set after adding single element: {'mango', 'apple', 'banana', 'cherry'}

In this example, we use the update() function to add the element mango to the set.

Using | Operator

We can use the | operator to add a single element to a set.

Suppose we have the same set as above.

We can use the following code to add the element lime to the set:

# Add a single element to the set
my_set = my_set | {"lime"}

# Show set
print("Updated set after adding single element:", my_set)

Output: 👇️

Updated set after adding single element: {'apple', 'banana', 'cherry', 'lime'}

In this example, we use the | operator to add the element lime to the set.