Skip to content

Python set add method | Example code

  • by

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 a 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 a 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 or suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading