Last Updated on May 12, 2024 by Roshan Parihar
To update set in Python, use the update()
function to add single or multiple elements. You can also use the add()
function to add a single element in a Set.
Let’s find out the use of these two functions below to add or update a set in Python.
Update Set with Single or Multiple Elements in Python
If you want to add or update single or multiple elements to a Set, you can use the update()
function in Python. You can pass single or multiple comma-separated elements within the curly brackets as the argument of the function.
Example 1
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
When the single or multiple specified elements are already present in the set variable, it does nothing with the matching element and updates the non-matching elements.
The above example shows the multiple elements added or updated to the set element. The function adds or updates 3 items in a set variable.
Add Single Element to a Set in Python
When you have to add only a single element to a Set variable, you can use the add()
function in 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 add()
function within the loop in Python.
Example 2
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.
Merge Two Sets in Python
In addition to the above methods, you can also add or update one set variable elements to another set variable. It requires using the update()
function as given in the example below.
Example 3
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’ are added to the first set variable ‘mySet1’.
You May Also Like to Read