We can add new items to sets in python like lists. So how can we insert a new member to a set? In this lesson, we will focus on Python Set Add methods and learn how to do this in Python Programming.
To insert a new item to a pyhton set, we will use a different methods than lists. As you remember , to add 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 insert a new item to a set. We will insert “Gimli” to the dwarves set.
You can also learn Python Set Intersection Method
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.