How to Add or Update Set in Python with Examples

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.

Output

{‘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.

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.

Output

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

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.

Output

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

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

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.