Python Set add() method with Examples

Python Set add() method

Now, we are going to learn about the add method. As the name of the method says, with the add method, we can add an element to the set. The thing is that the set only allows unique elements, so if the element that we are trying to add, already exists in the set, then the element won’t be added again. Let’s have a look at a simple program, which demonstrates the same thing.

Python Set add() method

As you can see, in the above program, we have a simple set, in which, there is some element, and then we are using the add method, to add some elements to the set. Now, we are trying to add the string ‘Programming’ to the set. Since it is not already there in the set, the element would be added to the set, and then we are also trying to print the set. Let’s have a look at the output of the above program.

{True, 3.1, ‘Programming’, ‘Python’, 29, ‘GyaniPandit’}

As you can see, since the string was not there in the set, it was added to the set. On the other hand, if the element was already present in the set, then it won’t be added again. Note that we have to provide the element that we want to add to the set, as an argument. If the element is not there in the set, it would be added. Also, the method returns None.

Have a look at the below program, in which, we are trying to add some element in the set, which is already there in the set, so it is not added again to the set. Let’s have a look at the demonstration.

As you can see, in the above program, we have a set, and in the set, we are trying to add an element, which is already there in the set. So, in such a situation, there is no effect, and the element is not added again to the set. Let’s have a look at the output.

{True, 3.1, ‘Python’, ‘GyaniPandit’, 29}

As you can see, the string ‘GyaniPandit’ was already in the set, so it was not added again. In this way, we can make use of the add method, to add some elements to the set. Remember that if the element is already present in the set, then the element is not added to the set. Also, we need to give the element as an argument, which we want to add to the set.