Nayablal Vishwakarma
PRO
last year
Nayablalcountry asked

In Python sets, it says items must be immutable. But we can still add, remove, or update items in a set. How is that possible?

Abhay Jajodia
Expert
last year
Abhay Jajodia answered

Hi Nayablal Vishwakarma,

A set is mutable, but the items inside the set must be immutable.

So you can change the set by adding or removing items, but each item you put inside must be something that cannot change, like an int, float, str, or tuple.

Example:

s = {1, 2}
s.add(3)      # allowed
s.remove(1)   # allowed

But you cannot add a list, because a list can change:

s.add([4, 5])   # TypeError: unhashable type: 'list'

The reason is simple: sets use hashing to store items, and hashing only works safely when the item itself cannot change.

If you have more questions, I am here to help 😊

Python
This question was asked as part of the Getting started with Python course.