python set add function

Python set add() function

The set add() function of python is used to add a specified element into a set.

As we know, sets in mathematics do not allow repetition. Similarly, if you want to add an element already existing in a set, it will not add that.

set add() method in Python

Python set add() function syntax :

setvariable.add(element)

Example 1 :

s = {2,3,4,5}
s.add('a')
print(s)


Output :

{2, 3, 4, 5, 'a'}

Example 2:

s = {2,3,4,5}
s.add(2)
print(s)


Output :

{2, 3, 4, 5}

As you can see, 2 is not added because it is already there.

Example 3:

s = {2,3,4,5}
print(s.add(10))


Output :

None

β€œNone β€œ is because the return value of add method is none. And here, we print the s.add() method not β€œs”. That’s why we got None.

Example 4:

s = {2,3,4,5}
s.add("2")
print(s)


Output :

{2, 3, 4, 5, '2'}

In the above example, we add a β€œ2” as a string(because it is in double quotes)in a set. Therefore, both 2 can add in the set. But the types of both the 2 are different.

How to use python set add function with a Tuple :

Adding a tuple in a set we have two methods: add() method, update() method.

Example 5:

s = {2,3,4,5}
t=("a","b")
s.add(t)
print(s)


Output :

{2, 3, 4, 5, ('a', 'b')}

Example 6:

s = {2,3,4,5}
t=("a","b")
s.update(t)
print(s)


update function add a specified element into a set. But the position of adding an element depends upon the Python interpreter.

Output (First run) :

{2, 3, 4, 5, 'a', 'b'}

Output (Second run) :

{2, 3, 4, 5, 'b', 'a'}

Output (Third run) :

{2, 3, 4, 'a', 5, 'b'}

As you can see, each time your set is updated.

Adding a list in a Python set:

Important to note that list is added to the set only with the help of the update() method. Add a list with the help of add() method gives you an error.

Example 7:

s = {2,3,4,5}
l=["a","b"]
s.update(l)
print(s)


Output (First run) :

{2, 3, 4, 5, 'b', 'a'}

Output (Second run) :

{2, 3, 4, 5, 'a', 'b'}

Example 8:

s = {2,3,4,5}
l=["a","b"]
s.add(l)
print(s)


Output :

Traceback (most recent call last):
Β  File "E:\Python files\kmtomile.py", line 31, in <module>
   s.add(l)
TypeError: unhashable type: 'list'

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!