Member-only story
Hi everyone, welcome back. In these examples, we will be going over how to add elements into a set in Python. Sets can be used to store a collection of data. A set in Python does not allow duplicate values. The elements within a set are immutable, though elements can still be added or removed. The elements within a set are unordered and unindexed. With this introduction out of the way, let’s get into it.

Creating Set
Let’s start by creating our set:
mySet = {1, 2, 3}
print(mySet)Output:
{1, 2, 3}
So now, we have a populated set with a few elements. We can verify that it was successfully created and populated by printing the set and checking the output. Now let’s see how we can add elements.
Adding Elements Into The Set
Let’s try to add an element into our set. We can do this by using the built in add() function that is provided. Let’s see an example:
mySet = {1, 2, 3}
mySet.add(4)
print(mySet)Output:
{1, 2, 3, 4}
In the example above, we can see that we added a new number into our set by using the add() function. We can verify that it was successfully added by printing the set and checking the output.
Let’s see what happens if we try to add a duplicate value:
mySet = {1, 2, 3}
mySet.add(3)
print(mySet)Output:
{1, 2, 3}
In this example, we tried to add a new number of a value that already exists. As we can see in the output, the duplicate value was not successfully added because sets do not allow duplicate values.
Now, let’s see how we can add the elements of one set to another. We can do this by using the built in update() function that is provided. Let’s see an example:
mySet = {1, 2, 3}
mySecondSet = {4, 5}
mySet.update(mySecondSet)
print(mySet)Output:
{1, 2, 3, 4, 5}
In the example above, we can see that we have added the elements of our second set into our first set. We can verify that the elements were successfully added by printing our set and checking the output. The update() function can be used to add any iterable object such as a list or a tuple.
Conclusion
That is it for adding elements into a set in Python. We covered how to add elements by using the add() function and how to add elements from other iterable objects by using the update() function. I hope this helps. If there are any questions or comments, please let me know. Thanks for reading.