When learning Python, you will inevitably encounter the concepts of mutable and immutable data types.
All the discussions below are based on memory addresses.
- Immutable data types: When the value of a variable of this type changes, its corresponding memory address also changes. Such data types are called immutable.
- Mutable data types: When the value of a variable of this type changes, its corresponding memory address remains unchnaged. Such data type are called mutable.
Summary: For immutable types, modifying the value changes the memory address; for mutable types, modifying the value does not change the memory address.
Python's Six Data Types
Python has six data types: numeric, string, list, tuple, dictionary, and set.
Among them, the immutable types include three: numeric, string, and tuple.
The remaining three are mutable types: list, dictionary, and set.
Mutable Types
- The value of an object can be modified, and the memory address of the object remains unchanged after modification.
- Mutable types include: list, dictionary, and mutable set.
>>> s = [1, 2, 3, 4, 5]
>>> id(s)
2115225773704
>>> s[2] = "a"
>>> s
[1, 2, 'a', 4, 5]
>>> id(s)
2115225773704
>>> d = {"name": "bone", "age": 26}
>>> id(d)
2115223112656
>>> d["age"] = 25
>>> d
{'name': 'bone', 'age': 25}
>>> id(d)
2115223112656
>>> a = {1, 2, 3}
>>> id(a)
2115225769128
>>> a.add(4)
>>> id(a)
2115225769128
>>> a
{1, 2, 3, 4}
Immutable Types
- Once the value changes, the memory address changes; it is equivalent to redefining the variable.
- When attempting to modify the element of a object, a new memory space is actually allocated to store the new value.
- Immutable types include: numeric, tuple, string, and frozenset.
- Objects of immutable types do not have methods that modify them in place; attempting to use such methods results in an error.
>>> a = (1,2,3)
>>> a[1] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a = "bone"
>>> a[1: 3] = "x"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> a = frozenset({1, 2, 3})
>>> a
frozenset({1, 2, 3})
>>> id(a)
2115225768456
>>> a.add(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'