In Python, to add to a set, you can use the add() function. add() will add an element to the set if the element is not already in the set.

s = {1, 2, 3}

s.add(4)

print(s)

#Output:
{1, 2, 3, 4}

You can also use the update() function to add multiple elements from a list to a set.

s = {1, 2, 3}

s.update([4,5])
s.update({6,7})

print(s)

#Output:
{1, 2, 3, 4, 5, 6, 7}

When working with collections of data in Python, the ability to easily add items or change the collection is important.

One such case where you may want to modify a collection is if you want to add elements to a set in Python.

To add on item to a set in Python, you can use the add() function. add() will add an element to the set if the element is not already in the set.

Below shows a simple example of how you can use add() to add one item to a set in Python.

s = {1, 2, 3}

s.add(4)

print(s)

#Output:
{1, 2, 3, 4}

Adding Multiple Items to Set in Python with update()

If you want to add multiple items to a set in Python, then you could use the add() function multiple times, or use the update() function.

The update() function takes in an iterable object (such as a list or set) and adds it to the set.

Below shows you how to add multiple elements to a set using update() in Python.

s = {1, 2, 3}

s.update([4,5])
s.update({6,7})

print(s)

#Output:
{1, 2, 3, 4, 5, 6, 7}

Hopefully this article has been useful for you to learn how to add items to a set in Python.

Categorized in:

Python,

Last Update: March 22, 2024