Skip to main content

8.12) Object Mutability And Immutability


We’ve now introduced all the major object types in Python and talked about the concept of mutability and immutability. It’s useful to go over the concept again, to make sure you understand what you can and can’t do with specific types of objects.

  • Mutable objects are those that can be modified in place. Lists and dictionaries are mutable. For example you can modify individual elements of a list and add or delete elements.
  • Immutable objects are those that cannot be modified. So far we introduced strings and tuples as being immutable. You cannot change individual elements of a string or tuple.

Integers and floats are also immutable, they cannot be modified. You might wonder though, why you can change the value of a variable without an error:

>>> a=3
>>> print a
3
>>> a=4
>>> print a
4

What you have done here is just dump the integer 3 and create a new object 4, which is now referenced by the variable a. You’ve replaced the number 3 with the number 4 rather than modify the number 3.