Mutable v.s. Immutable
There are two types of objects[1]:
- immutable: objects can't be changed.
- mutable: objects can be changed.
Type | Immutable ? |
---|---|
int | ✅ |
float | ✅ |
bool | ✅ |
complex | ✅ |
tuple | ✅ |
frozenset | ✅ |
str | ✅ |
list | 🚫 (mutable) |
set | 🚫 (mutable) |
dict | 🚫 (mutable) |
custom class | 🚫 (mutable) |
Let's see an example: int
is immutable, if we tried to modify this value with addition, then you'd get a new object.
>>> x = 5
>>> id(x)
9793216
>>> x += 1
>>> id(x)
9793248 # a new object
>>> a = "test"
>>> id(a)
139661423109424
>>> a += "_test"
>>> id(a)
139661423109552 # a new object
>>>
Consider with a mutable object, like list:
>>> a = [1,2,3]
>>> id(a)
140586760807680
>>> a.append(10)
>>> id(a)
140586760807680 # still the same memory address
>>>