Skip to content

Is set mutable in Python?

  • by

Yes, Python sets are mutable because the set itself may be modified, but the elements contained in the set must be of an immutable type.

Example code to check set mutable in Python

Simple example code. However, since Python sets are unordered, indexing doesn’t matter. We cannot access or change an element of a set using indexing or slicing.

Let’s try to add a single element into the set using the add() method.

my_set = {1, 3}
print(my_set)

my_set.add(2)
print(my_set)

Output: If the set is immutable then TypeError will throw by the compiler.

Is set mutable in Python

To add multiple elements use the update() method. The update() method can take tuples, lists, strings, or other sets as its argument.

my_set = {1, 3}
print(my_set)

my_set.update([2, 3, 4])
print(my_set)

Output:

{1, 3}
{1, 2, 3, 4}

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