set add() in python


In this tutorial, we are going to learn about the add method of set data structure. Let's dive into the tutorial.

Set data structure stores unique elements in it. The add method of set data structure takes an element and adds it to the set.

Follow the below steps to add a new element to the set.

  • Initialize a set.
  • Add a new element to the set using the add method.
  • Print the updated set.

Example

 Live Demo

# initialzing the set
numbers_set = {1, 2, 3, 4, 4, 5}
# adding an element to the set
numbers_set.add(6)
# printing the updated set
print(numbers_set)

Output

If you run the above code, then you will get the following result.

{1, 2, 3, 4, 5, 6}

We know that set only stores unique elements. What happens if we try to add an element that's already present in the set?

You won't find any difference in the set. See yourself by running the following code.

Example

 Live Demo

# initialzing the set
numbers_set = {1, 2, 3, 4, 5}
# adding an element to the set
numbers_set.add(4)
# printing the updated set
print(numbers_set)

Output

If you run the above code, then you will get the following result.

{1, 2, 3, 4, 5}

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 11-Jul-2020

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements