Python3: Mutable, Immutable… Everything is object!

Abidi Ghofrane
3 min readJan 17, 2020
Lame

Why is it important to know if an object is mutable or immutable in python?

Because, my friend, you need to know what you’re dealing with to know what to do facing any object!

Okay so what’s the difference?

Python has a lot of data structures that you can use to represent data, or combine them to create your own custom data. And the first thing to say about a data is if it’s value is changeable or no, in other words is it mutable or immutable.

Let’s start simple!

well, we know that any variable(or data) has it’s own memory allocation. we can access a certain variable’s memory address with a function called id()

id()

And of course, each variable has it’s own type. As we all know, everything in python belongs to a certain class. so even types are actually classes. And to access a certain variable’s type we use the type() function. here are some examples;

type()

A variable refers to an object, for example, in our previous example b refers to the object “this is a string”. An object can be referred to by more than one variable name:

Mutable and immutable objects:

Whenever an object is created, it is assigned a unique object id. The type of the object is defined at the runtime and we can’t change it later. Now is it’s state can be changed, it is a mutable object, and if it can’t means it’s immutable.

Mutable object: lists, dict, set

Immutable object: int, float, complex, string, tuple, frozen set [note: immutable version of set], bytes

To find out if an object is mutable we try a simple example

And now, we know for sure that lists are mutable since we can change a certain value in a list.

let’s see tuples:

So, we were able to append more elements to the tuple, but we couldn’t change a certain value. that’s what immutable is.

why does it matter and how differently does Python treat mutable and immutable objects?

it is important for when passing variables to functions to know how they should be treated. Memory efficiency is highly affected when the proper objects are used.

here’s an example:

The list kept it’s own id and the add is successful

Let’s try with an immutable type:

the string a did not change

Above, a was passed to change_str but did not change value, it’s because it was passed by value. which means only the value got passed and not the variable, unlike the one before it, which was passed by reference, so the object could be able to change. and there you have it! the difference between mutable and immutable!

--

--

Abidi Ghofrane

Software engineering student at Holberton School Tunis