How to Add or Update Set in Python

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


{‘Feroz’, ‘Ram’, 10, 11, 13.2, 17, ‘Shyam’, ‘Bilal’, ‘Rock’}

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


{‘Bilal’, ‘Shyam’, 10, 11, 13.2, ‘Ram’, ‘Feroz’}

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


{‘Ram’, ‘Rock’, ‘Bhanu’, ‘Feroz’, 10, 13.2, 19, ‘Bilal’, ‘Shyam’, 27}

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

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.