Append to set Python | Example code

Use The set add() method to append a given element into a set in Python. The new element will add only if the element is not present in the current set.

Use the update() method to add iterable objects into sets.

Note: The add() method use only add one item into the set.

Example append to set Python

Simple example code.

Note: Once a set is created, you cannot change its elements, but you can add new elements.

my_set = {2, 3, 5, 7}

my_set.add(11)

print(my_set)

Output:

Append to set Python

Add sets

Use the update() method to add items from another set into the current set.

my_set = {2, 3, 5, 7}
second_set = {'A', 'B'}

my_set.update(second_set)

print(my_set)

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

Add tuple to a set

You can add any iterable object (tuples, lists, dictionaries, etc.) with this method.

my_set = {'A', 'B', 'C'}
tup = ('i', 'o')

my_set.update(tup)

print(my_set)

Output: {‘B’, ‘i’, ‘C’, ‘o’, ‘A’}

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

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.