Mutable and Immutable Objects in Python3

Rodrigo Sierra Vargas
4 min readMay 28, 2019

--

Introduction

As a Python and programming newcomer, I have found interesting and almost magic things that can happen inside a computer machine, and how each programming language has its own tricks and deep applications of primary concepts of computer science. In this review, I want to show some properties of mutable and immutable objects and how Python treat them and how that is is related to passing arguments to functions.

id and type

id(object) is a built-in function in Python that accepts a single parameter and is used to return the identity of an object which is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same value. For CPython implementations, this is the address of the object in memory. On the other hand, the built-in method type(object) returns the type of the passed object. Python has five standard data types: Numbers (int(), long(), float(), complex()), String, List, Tuple and Dictionary.

Mutable objects

In Python mutable objects are Lists, Sets, and Dictionaries. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can’t be changed afterward. However, it’s state can be changed if it is a mutable object, the value of a mutable object can be modified in place after its creation.

Immutable objects

On the contrary, exist immutable objects that are replaced in case of a change or simply they don’t accept the change, and that’s the case for the following types:

Why does it matter and how differently does Python treat mutable and immutable objects

As it’s seen below, the list “colors” has an id and a type that remains after adding a new color which proves that lists are mutable.

And here is an example of what happens when we try to change an immutable object:

when we change the value of “number” Python changes its id because an int is immutable so it can’t assign another value to the first id. In the other case, an error is raised by the system with the confirmation that a string doesn’t support assignment.

How arguments are passed to functions and what does that imply for mutable and immutable objects

Due to the state of immutable objects, if an integer or string value is changed inside a function block then it much behaves like an object copying. A local new duplicate copy of the caller object inside the function block scope is created and manipulated.

If the value of a mutable object is changed inside the function block scope then its value is also changed inside the caller or main block scope regardless of the name of the argument.

References:

https://svn.python.org/projects/python/trunk/Objects/intobject.c

--

--