We can add new items to sets in python like lists. So how can we add a new member to a set? In this lesson, we will focus on Python Set Add methods and learn this.
To add a new item to a pyhton set, we will use a different method than lists. As you remember , to ad a new item to a list, there is an append method. In sets, there is another method for this and the name of this method is add method. We can use add method to add a new item to a python set.
Let’s give an example and leaarn how to use this python set add method. Below, we will add a new item to a set. We will add “Gimli” to the dwarves set.
The output will give us the set which includes the new item.
We can also use a different method to add new members to a set. For example, we can update an existing set with the members of another set. To do this, we will use python set update method.
In the below exaple, we will see how to use pdate method in python programming.
We will get the below autpu fort his code:
As you can see, our fisrt set is updated with the new items.
Let’s also give an exampel with number sets.
As an output, we will get an updated number1 set like below:
In this lesson, we have learned Python Set Add methods. We have seen how to add a one or more item to the existing python set. This method is one of the most used methods with python set data types.