set add() in python
The Python set add() method adds a given element to a set if the element is not present in the set in Python.
Syntax: set.add( elem )
Parameters:
- elem: The element that needs to be added to a set.
Returns: None
Adding a new element to a set
It is used to add a new element to the set if it is not existing in a set.
Python
# set of lettersGEEK = {'g', 'e', 'k'}# adding 's'GEEK.add('s')print("Letters are:", GEEK)# adding 's' againGEEK.add('s')print("Letters are:", GEEK) |
Output:
Letters are: {'e', 's', 'g', 'k'}
Letters are: {'e', 's', 'g', 'k'}Adding element in a set that already exists
It is used to add a existing element to the set if it is existing in a set and check if it gets added or not.
Python
# set of lettersGEEK = {6, 0, 4}# adding 1GEEK.add(1)print('Letters are:', GEEK)# adding 0GEEK.add(0)print('Letters are:', GEEK) |
Output:
Letters are: {0, 1, 4, 6}
Letters are: {0, 1, 4, 6}Adding any iterable to a set
We can add any iterable to a set using add or update function, if we try to add a list using the add function we get a unhashable Type error.
Python
# Python code to demonstrate addition of tuple to a set.s = {'g', 'e', 'e', 'k', 's'}t = ('f', 'o')l=['a','e']# adding tuple t to set s.s.add(t)# adding list l to set s.s.update(l)print(s) |
Output :
{'a', 'g', 'k', 'e', ('f', 'o'), 's'}

