Python3: Mutable, Immutable… everything is an object!

khouzem boussaid
3 min readOct 5, 2021

Introduction

First things first, let’s explain this.

Everything is an object, everything (all values) in Python is an object or a class. For example, an integer in Python is an object, a large block of “structured” memory, typically over 100 bits long, and different parts of that structure are used internally by the interpreter. This means that things such as integers, floats, structures of data, functions, and strings are all objects. They can all be stored in variables, passed between functions, and even be returned from them. Variables are simply references and don’t hold data themselves, kind of like a pointer.

Id and type

id

All objects in Python have their unique id, the id is assigned to the object when it is created, the id is the object’s memory address, and will be different for each time you run the program.

Type

Type() the method returns the class type of the argument(object) passed as a parameter. type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of given object. If three arguments type(name, bases, dict) are passed, it returns a new type of object.

Mutable objects

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.

Immutable objects

Immutable is when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.

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

Python handles mutable and immutable objects differently. Immutable is quicker to access than mutable objects. Mutable objects are great to use when you need to change the size of the object, for example: list, dict, etc... Immutables are used when you need to ensure that the object you made will always stay the same.

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

First, you need to understand how Python stores variables before we go further. This will help you to understand the behavior of Python mutable and immutable function arguments. In Python, almost everything is an object. Numbers, strings, functions, classes, modules, and even Python compiled code, all are objects.

Python treats all variables as references to the object. This means all variables store the memory address of the actual object. This concept is much like “Pointer” in C and C++ programming languages. This means the address of the actual object is stored in the Python named variable, not the value itself.

--

--