In this tutorial we are going to learn all about Python set add() method along with some examples. add function in python is used to add items in the set.
In the previous tutorial, we have seen all about python set along with some examples.
I recommend, before going through this tutorial, please check out our previous python set tutorial.
Headings of Contents
Python Set add() Method
add function in python is used to add items in the set. If the specified item already exists in the set, then it will not add the item. add function in python accepts items as parameters.
Syntax
The syntax of add function in python is:-
set.add(item)
Parameter
add function in python takes item to be add in the set.
- item:- Required, item to be add in the set.
Python set add() exmaple
Here we will take some examples of python set add method.
Example 1:
my_set = { 1, 2, 3, 4, 5, 6, 7 }
print(my_set)
my_set.add(8)
print(my_set)
Output
{ 1, 2, 3, 4, 5, 6, 7 }
{ 1, 2, 3, 4, 5, 6, 7, 8 }
Example 2:
What happen. If item already exists in the set.
my_set = { 1, 2, 3, 4, 5, 6, 7 }
print(my_set)
my_set.add(7)
print(my_set)
Output
{ 1, 2, 3, 4, 5, 6, 7 }
{ 1, 2, 3, 4, 5, 6, 7 }
Note:- If an item already exists in the set, Then Python set add function will not add that item to the set.
Conclusion
In this tutorial, you have learned all about the python set add method to add items in the set. If a specified item already exists in the set, Then the set add function will not add that item to the set.
I hope this article will help you. If you like this article, please share it with your friends who want to learn Python programming from scratch.
For More Information:- Click Here