Python Set add() Method

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.




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

Visual Representation of How to Use Python Set add() Method

Example 1: How to Use Set add() Method

# set of letters
data = {19, 21, 46}
print("Letter before adding: ", data) 

# Adding 11 element
print("Letters after adding: ", data)


Letters before adding: {19, 21, 46}
Letters after adding: {11, 46, 19, 21}

Example 2: Adding an element in a set that already exists

Visual Representation of 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
print("After adding an element to set is: ", name)


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

print("After adding: ", name)


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

Python Set discard()

Python Set clear()

Python Set difference()

Python difference_update()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.