How to Add an Item to a Set in Python



Python


In this article, we show how to add an item to a set in Python.

A set in Python is a collection of unique values.

We can add an item to a set in Python using the add() function.

With the following code in Python, shown below, we get the following output.





So let's go over this code now.

So we created a set, set1, which has the items: 1,2,3,4.

We then take this set1 and add in the item, 8.

This gives us a set of, 1,2,3,4,8

We then take the same set and add in the item, 3.

Because a set is a collection of unique items, it doesn't change the set, because 3 already exists in it. Therefore, we have the same set as before we ran this function.

And this is all that is required to add an item to a set in Python.


Related Resources



HTML Comment Box is loading comments...