Python:Mutable, Immutable… everything is object!

1)Introduction

Othmaniamir
3 min readJun 22, 2021

A lot of Python books often mention that “everything in Python is an object”, and “objects are first class citizens”, but they don’t always explain what that these things actually mean. Let’s try to fix that up now. In Python, everything is an object, and everyone who wants to learn Python should understand from the beginning that objects in this programming language can be either mutable or immutable.

2)id and type

The built-in function id() returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory, although this is specific to the Python implementation and the platform being used. The is operator compares the identity of two objects. The built-in function type() returns the type of an object.

The type of an object is itself an object. This type object is uniquely defined and is always the same for all instances of a given type. Therefore, the type can be compared using the is operator. All type objects are assigned names that can be used to perform type checking. Most of these names are built-ins, such as list, dict, and file.

3)Mutable objects

A mutable object is a changeable object that can be modified after it is created.

4) Immutable object

An immutable object is an object whose state can never be modified after it is created.

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

Immutable objects are accessible in a quicker way than mutable objects.

Changing Immutable objects is fundamentally expensive as it involves creating a copy; but, changing mutable objects is considered cheap

6)how arguments are passed to functions and what does that imply for mutable and immutable objects

Its important for us to know difference between mutable and immutable types and how they are treated when passed onto functions .Memory efficiency is highly affected when the proper objects are used.

For example if a mutable object is called by reference in a function, it can change the original variable itself. Hence to avoid this, the original variable needs to be copied to another variable. Immutable objects can be called by reference because its value cannot be changed anyways.

As we can see from the above example, we have called the list via call by reference, so the changes are made to the original list itself.

Lets take a look at another example:

In the above example the same object is passed to the function, but the variables value doesn’t change even though the object is identical. This is called pass by value. So what is exactly happening here? When the value is called by the function, only the value of the variable is passed, not the object itself. So the variable referencing the object is not changed, but the object itself is being changed but within the function scope only. Hence the change is not reflected.

--

--