Ruben Oliveros
3 min readJan 13, 2021

--

Python3: Mutable, Immutable… everything is an object!

Takeaway and TLDR

Objects are everything Python processes and funny enough, it references them with memory addresses (yes, with pointers). Some objects are mutable and others are immutable.

Want to know more?

Introduction

By now you already know Python is an Object-oriented programming (OOP) language, and it takes this paradigm in the sense that objects can be assigned to a variable or passed as an argument to a function. Keep in mind these objects could be liable to change or unable to be changed.

ID and Type

Two very important commands. The function type() allows us to see what kind of object we are dealing with and id() returns the identity of an object, and by that we mean the unique integer that the object will be associated with while it exists in memory.

Example of ID & Type with a string
Example of ID & Type with an integer

Some of the mutable data types in Python are list, dictionary, set, and user-defined classes. On the other hand, some of the immutable data types are int, float, decimal, bool, string, tuple, and range.

Mutable Objects

Instead of writing here which objects are mutable and which are not, I found for you this handy table so you can refer to it every time you need it.

A handy table used in this post http://bit.ly/38Apdf0

As you might suspect already, a mutable object is more often used by our scripts to get things done.

Immutable Objects

But sometimes we don’t need those objects to change, that's why Python has the classes that are checked immutable on the table right up. Those are used when the information contained in them is a fixed reference that our code needs to work properly. If you really need to change it, you have to clone it into a mutable, make the changes necessary, and get it back to an immutable object.

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

Because immutable objects have a fixed value, meaning they are not expected to change therefore no method is in place to do so, they are quicker to access compared to mutable objects that need methods to modify them.

In contrast, because of all the hassle involved in modifying an immutable object, mutable objects are less taxing to change making them the obvious choice when we need to store a temporary value.

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

Functions get immutable objects by their reference since there is no other method available. When a mutable object is passed to a function, a copy is passed instead, making this procedure a good way to waste memory

--

--