Python Programming Language: How to Add Elements To a Set

Jesse L
2 min readJun 29, 2022

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…

--

--

Jesse L
Jesse L

Written by Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.

No responses yet