AppDividend
Latest Code Tutorials

Python Set add() Method Example Tutorial

0

Python set add() is an inbuilt function that is used to add an element to any set. 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() method 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 the 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 Python set add() method works

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 small ‘d’, then it would also not be added to the set because ‘d’ is also present.

How to add tuple to set

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'
# 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.

See also

Python list

Python dictionary

Leave A Reply

Your email address will not be published.

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