Are Sets Mutable in Python?
Last Updated :
03 Dec, 2024
Improve
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:
# 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:
- You can add elements to a set after it is created.
- You can remove elements from a set.
- You can update a set by performing set operations (like union, intersection, etc.).