Python Set add: How to Add Element to Set

0
4
Python Set add() Method Example Tutorial

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

Python set add()

The set add() in Python is a built-in method that adds an element to the set if the element is not present in the set. If you want to insert the new item in the set, then you can use the Python set add() method.

Syntax

set.add(element)

Here, an element is a value that is 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 present 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'}

Here in this example, we can see that though we have added ‘a’ and ‘D’ in 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’, then it would also not be added to the set because ‘d’ is also present.

How to add 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 Reply

Please enter your comment!
Please enter your name here

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