Open In App

Are Sets Mutable in Python?

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Yes, sets are mutable in Python. This means that you can modify the contents of a set after it has been created. You can add or remove elements from a set but like dictionaries, the elements within a set must be immutable types.

Example of Mutability in Sets

Adding Elements to a Set

You can add elements to a set using add() method:

Python
# Creating a set
s = {1, 2, 3}

# Adding a new element
s.add(4)

print(s)  

Output
{1, 2, 3, 4}

What Does It Mean for Sets to Be Mutable?

When we say that sets are mutable, we mean that:

  1. You can add elements to a set after it is created.
  2. You can remove elements from a set.
  3. You can update a set by performing set operations (like union, intersection, etc.).

Next Article
Article Tags :
Practice Tags :

Similar Reads