Python Set add() method is used to add an element to a set if the element is not present in the set.
The add() method only adds one element at a time. To add multiple elements, you can use the update() method instead.
Syntax
set.add(element)
Parameters
element: It is an element that is added to the set.
Return Value
It does not return any value or anything. It just adds the given value if it is not in that set.
Visual Representation
Example 1: How to Use Set add() Method
# set of letters
data = {19, 21, 46}
print("Letter before adding: ", data)
# Adding 11 element
data.add(11)
print("Letters after adding: ", data)
Output
Letters before adding: {19, 21, 46}
Letters after adding: {11, 46, 19, 21}
Example 2: Adding an element in a set that already exists
name = {'A', 'p', 'd', 'i', 'v', 'e', 'n'}
print("Before adding an element to set is: ", name)
# So we will again add 'p' using add() method
name.add('p')
print("After adding an element to set is: ", name)
Output
Before adding an element to a set: {'p', 'i', 'd', 'A', 'e', 'n', 'v'}
After adding an element set: {'p', 'i', 'd', 'A', 'e', 'n', 'v'}
As you can see there is no difference in the output because ‘p‘ element already exists in the set.
Example 3: Adding a tuple to a set
# Writing Appdividend char by char in a set
name = {'A', 'p', 'd', 'i', 'v', 'i', 'd', 'e', 'n'}
print("Before adding: ", name)
# Here we have not included one 'p' and 'd'
# Here, we will add 'p' and 'd' in a tuple
# Then we will add it to the set
tup = ('p', 'd')
# adding
name.add(tup)
print("After adding: ", name)
Output
Before adding: {'d', 'p', 'A', 'n', 'e', 'i', 'v'}
After adding: {'d', 'p', 'A', 'n', 'e', 'i', ('p', 'd'), 'v'}
But in this example, we can see that both “a” and “d” are added to the set because they are in a tuple, so they are treated as a tuple by the set, not as a single character.
Related posts
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.