Mutable vs. Immutable (Python)

Immutable data types

  • They are not modifiable
  • e.g. Numbers, Strings and Tuples
>>> a = 1
>>> b = a
>>> b = b + 1
>>> print(a)
1
>>> print(b)
2
Before line 3
a ---> 1
b -----^
At line 3 It creates a new value for the name b, because numbers are immutable.
After line 3
a ---> 1
b ---> 2

Mutable data types

  • They are modifiable
  • e.g. Lists, Dictionaries and Sets
>>> a = [1,2,3]
>>> b = a
>>> b += [4]
>>> print(a)
[1, 2, 3, 4]
>>> print(b)
[1, 2, 3, 4]
Before line 3
a ---> [1,2,3]
b -----^
At line 3 It changes the value of both names, because lists are mutable.
After line 3
a ---> [1,2,3,4]
b -----^

Example

>>> a = [1,2,3]
>>> for i in a:
...   i += 1
...
>>> print(a)
[1, 2, 3]
>>> for i in range(len(a)):
...   a[i] += 1
...
>>> print(a)
[2, 3, 4]
  • In line 3 it creates a new value and assigns it to i. (Does not modify the list.)
  • In line 7 it creates a new value and assigns it to a[i]. (Does modify the list.)