Set add() Method in Python
Last Updated :
20 Dec, 2023
The Python set add() method adds a given element to a set if the element is not present in the set in Python.
Example: Add Element to an Empty set
It is used to add a new element to the empty set.
Python3
GEEK = set ()
GEEK.add( 's' )
print ( "Letters are:" , GEEK)
GEEK.add( 'e' )
print ( "Letters are:" , GEEK)
GEEK.add( 's' )
print ( "Letters are:" , GEEK)
|
Output
Letters are: {'s'}
Letters are: {'e', 's'}
Letters are: {'e', 's'}
Set add() Syntax
Syntax: set.add( elem )
Parameters
- elem: The element that needs to be added to a set.
Return
The add() method does not return anything
What is set add() Method
In Python, a set is an unordered collection of unique elements. The add() method is a built-in method in Python that is used to add a single element to a set. If the element is already present in the set, the set remains unchanged.
Python Set add() Method Examples
Before going to the example we are assuming the time complexity of the set.add() function is O(1) because the set is implemented using a hash table.
Now let’s look at some use cases of add() function in Python with examples:
- Add Element to an Empty set
- Add a new element to a Python set
- Add an element in a set that already exists
- Adding any iterable to a set
1. Add Element to an Empty set
It is used to add a new element to the empty set.
Python3
GEEK = set ()
GEEK.add( 's' )
print ( "Letters are:" , GEEK)
GEEK.add( 'e' )
print ( "Letters are:" , GEEK)
GEEK.add( 's' )
print ( "Letters are:" , GEEK)
|
Output
Letters are: {'s'}
Letters are: {'e', 's'}
Letters are: {'e', 's'}
2. Add a new element to a Python set
It is used to add a new element to the set if it is not existing in a set.
Python3
GEEK = { 'g' , 'e' , 'k' }
GEEK.add( 's' )
print ( "Letters are:" , GEEK)
GEEK.add( 's' )
print ( "Letters are:" , GEEK)
|
Output:
Letters are: {'e', 's', 'g', 'k'}
Letters are: {'e', 's', 'g', 'k'}
3. Add element in a set that already exists
It is used to add an existing element to the set if it is existing in the Python set and check if it gets added or not.
Python3
GEEK = { 6 , 0 , 4 }
GEEK.add( 1 )
print ( 'Letters are:' , GEEK)
GEEK.add( 0 )
print ( 'Letters are:' , GEEK)
|
Output:
Letters are: {0, 1, 4, 6}
Letters are: {0, 1, 4, 6}
4. Adding any iterable to a set
We can add any Python iterable to a set using Python add or Python update function, if we try to add a list using the add function we get an unhashable Type error.
Python3
s = { 'g' , 'e' , 'e' , 'k' , 's' }
t = ( 'f' , 'o' )
l = [ 'a' , 'e' ]
s.add(t)
s.update(l)
print (s)
|
Output :
{'a', 'g', 'k', 'e', ('f', 'o'), 's'}
In this article we covered the add() function in Python. Set add() method in Python is useful to avoid entry of duplicate item in the set.
Please Login to comment...