Python set add method | Example code

Using add method you can add a given element to an existing set. If a given element already presents in the list then it will not add because the set has unique values.

set.add(elem)

However, you can’t change sets after created but you can add new items.

Python set add example

Simple example code.

my_set = {2, 3, 5, 7}

# add 11 to set
my_set.add(11)

print(my_set)

Output:

Python set add method

Add tuple to a set

You can also add tuple into a set using add() method.

my_set = {2, 3, 5, 7}
tup = ('A', 'B')

# add 11 to set
my_set.add(tup)

print(my_set)

Output: {2, 3, 5, 7, (‘A’, ‘B’)}

Add Sets

If you want to add sets into sets then use the update() method. Using add method to add sets in to set will throw an error (TypeError: unhashable type: ‘set’).

Using the update() method you can add Any Iterable object.

my_set = {2, 3, 5, 7}
thisset = {"apple", "banana", "cherry"}

# add 11 to set
my_set.update(thisset)

print(my_set)

Output: {2, 3, ‘banana’, 5, ‘cherry’, 7, ‘apple’}

Do comment if you have any doubts and suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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