Last Updated on June 8, 2021 by Roshan Parihar
In this tutorial, learn how to add or update set in Python. The short answer is to use the add()
of Python to add a single element to the Set variable.
You can also update set in Python using the update()
of Python. The function is also useful to add multiple elements together to a Set in Python.
Let’s find out the use of these two functions below to add or update set in Python.
How to Add Single Element to Set in Python
To add a single element to a Set variable, you have to use the add()
function of Python. It takes a single element as the argument to add to the set variable. If the specified element is already present in the variable, the function does nothing. You also cannot use the function within the loop in Python. See the example below that shows the addition of a single element to a set.
1 2 3 4 5 6 7 8 |
#declare Set in Python mySet = {"Ram", "Shyam", 10, "Bilal", 13.2, "Feroz"} #Add elements to a Set mySet.add(11) #Print set print(mySet) |
Output
The above example added the single element 10 to a set variable. After it adds a single element to the variable, the size of the variable increases to 7 items.
Append Multiple Elements in Python
You can also add or append multiple elements to set in Python using the update()
function. The function can be used to add single or multiple elements to a set. You can pass single or multiple comma-separated elements within the curly brackets as the argument of the function.
If the single or multiple specified elements already present in the set variable, it does nothing with the matching element and updates the non-matching elements.
1 2 3 4 5 6 7 8 |
#declare Set in Python mySet = {"Ram", "Shyam", 10, "Bilal", 13.2, "Feroz"} #Add multiple elements to a Set mySet.update({11, 17, "Rock"}) #Print set print(mySet) |
Output
The above example shows the multiple elements added or updated to the set element. The function adds or update 3 items in a set variable.
Update Set in Python
In addition to the above methods, you can also add one set variable elements to another set variable. It requires using the update()
function as given in the example below.
1 2 3 4 5 6 7 8 9 |
#declare Set in Python mySet1 = {"Ram", "Shyam", 10, "Bilal", 13.2, "Feroz"} mySet2 = {"Bhanu", 19, 27, "Rock"} #Update elements to a Set mySet1.update(mySet2) #Print set print(mySet1) |
Output
The output shows all the elements of the second set ‘mySet2’ is added to the first set variable ‘mySet1’.
You May Also Like to Read