How to Add Element to Set in Python

The set add() method adds a given item to a set if the element is not present. If the element is already present in that set, it does not add it because, as we know, the set does not contain any duplicate value.

Python add to set

To add elements to the set in Python, use the set.add() method. The set add() in Python is a built-in method that adds an element to the set if the element is not present. To insert the new element in the set, use the set add() method.

Syntax

set.add(element)

Parameters

An element is a value to be added to the set.

Return Value

The set() method does not return any value or anything. It just adds the given value if it is not in that set.

How does the Python set add() method work?

See the following code.

# app.py
# Writing Appdividend char by char in a set
name = {'A', 'p', 'd', 'i', 'v', 'i', 'd', 'e', 'n'}

print("Before adding set is: ", name)

# here we have not included one 'p' and 'd'
# So we will add that using add() method
name.add('p')
name.add('D')
print("After adding set is: ", name)

Output

Before adding set is:  {'e', 'A', 'd', 'n', 'p', 'v', 'i'}
After adding set is:  {'e', 'A', 'd', 'n', 'p', 'v', 'D', 'i'}

In this example, we can see that though we have added “a” and “D” in the output, only “D” is added.

This is because “a” is already present in the set, so it cannot be added twice. On the other hand, if we could try to add a small “d”, it would also not be added to the set because ‘d’ is also present.

How to add a tuple to set

To add a tuple to a set, use the set() method. Add the following code.

# app.py

# Writing Appdividend char by char in a set
name = {'A', 'p', 'd', 'i', 'v', 'i', 'd', 'e', 'n'}

print("Before adding set is: ", 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 tuple, set is: ", name)

Output

Before adding set is:  {'d', 'p', 'A', 'n', 'e', 'i', 'v'}
After adding tuple, set is:  {'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 pop()

Python set length

Leave a Comment

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