Join Regular Classroom : Visit ClassroomTech

Python Set – add() method

It is a method in python set that adds element to the current set. If it’s already present it doesn’t add the element. It doesn’t return any value and modifies the given set. This method takes a single parameter. add() method cannot take multiple iterables but update() can.

Syntax:
set.add(iterable_element)

Also Read: Python Set – update() method

Example 1:

# Python code to understand add() method in set
# www.codewindow.in

s = {"amazing", "code"}
s.update("best")
print(s)

Output:

{'e', 'amazing', 'code', 'b', 't', 's'}

Explanation:
Here all the iterables in the word “best” is added to the parent set (s).

Example 2:

# Python code to understand add() method in set
# www.codewindow.in

s = {5, 8, 4}
s1 = (1, 5, 9)
s.add(s1)
print(s)

Output:

{8, 4, 5, (1, 5, 9)}

Explanation:
Here the tuple is added to the parent set as a single element.
Note: If a dictionary is used as an iterable, the keys gets updated to the set, not the values.


Follow Us

You Missed

Also Checkout