Python Set Add

python-set-add-method-ipcisco.jpg

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


 

 

dwarves = {"Thorin", "Balin", "Dwalin"}
dwarves.add("Gimli")
print(dwarves)

 

The output will give us the set which includes the new item.

 

{'Gimli', 'Thorin', 'Dwalin', 'Balin'}

 

python-set-add-method-ipcisco.jpg

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.

 

dwarves1 = {"Thorin", "Balin", "Dwalin"}
dwarves2 = {"Gimli", "Bofur"}
dwarves1.update(dwarves2)
print(dwarves1)

 

We will get the below autpu fort his code:

 

{'Bofur', 'Dwalin', 'Balin', 'Gimli', 'Thorin'}

 

python-set-update-method-ipcisco.com

As you can see, our fisrt set is updated with the new items.

 

Let’s also give an exampel with number sets.

 

numbers1 = {15,12,16,18,14}
numbers2 = {100,200,300,400}
numbers1.update(numbers2)
print(numbers1)

 

As an output, we will get an updated number1 set like below:

 

{100, 200, 12, 300, 14, 15, 16, 400, 18}

 

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.

 

Back to: Python Programming Course > Python Sets

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand