The Python set add() method adds a given element to a set if the element is not present in the set in Python.

Parameters:

• elem: The element that needs to be added to a set.

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.

• Add Element to an Empty set
• Add a new element to a Python set
• Adding any iterable to a set

Add Element to an Empty set

It is used to add a new element to the empty set.

Python3

Output

Letters are: {'s'}
Letters are: {'e', 's'}
Letters are: {'e', 's'}

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

 # set of letters GEEK = {'g', 'e', 'k'}   # adding 's' GEEK.add('s') print("Letters are:", GEEK)   # adding 's' again GEEK.add('s') print("Letters are:", GEEK)

Output:

Letters are: {'e', 's', 'g', 'k'}
Letters are: {'e', 's', 'g', 'k'}

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

 # set of letters GEEK = {6, 0, 4}   # adding 1 GEEK.add(1) print('Letters are:', GEEK)   # adding 0 GEEK.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 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

 # 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'}

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!