Python3: Mutable, Immutable... everything is object!
Daniela Morales
Software Engineer | Python & Golang Developer | Data Science Engineering Student
INTRODUCTION
Below in this article you will understand that in python everything we know as lists dictionaries tuples arrays among other things more than daily as programmers we use, as we have already seen classes we understood that for example: a class in python for example can be of type list type tuple type int etc ... and these super classes, to say the least, were generated from the instances in which we created the objects but after all, as most likely, you already know or if it is not that in python ALL ARE OBJECTS!.
So let's get started!
ID AND TYPE
Here we start by talking about how we can know the memory address of an object in CPython and an object as I already said I mean any method or variable declared in python and how can we know this? It is simple with the function id () this function gets us the memory address of our instance created, an example would be this:
REMINDER: id() is a built-in function in Python, which returns the identity of an object. The identity is a unique integer for that object during its lifetime. This is also the address of the object in memory.
Now the other part the type () function that makes this function the type () function that, as its name suggests, and you do not have to break your head much to fall into account, we are shown the TYPE of the data that we "passed as an argument", remember, between the parentheses.
Let's see an example:
The type () function tells us that the numeric data '243' that we pass to it as an argument is data of type INT, an 'integer', an integer.
MUTABLE OBJECTS IN PYTHON
Mutable objects or that can be 'changed' in python means that we can manipulate them for example the lists are mutable we can modify them the mutable ones are the most "complex" to use in programming (usually data structures like: dict, list, etc. ) and not only because they are more complex because they are structures that have things, but they usually mess with the issue of pointers; and paradoxically they are the least damaging to memory (they are written only once and are always reused). It must be said that the mutables are designed this way, because copying an entire data structure (although it can) would take a long time and would imply using a lot of memory to surely not take advantage of the copy (copying a String object is not the same as copying a list with millions of String objects, for later not having needed the copy; it becomes a waste of processor and memory).
A example would be:
in the previous example as we can see we are modifying the list in position zero we modify its value in this position by the integer '5'.
IMMUTABLE OBJECTS
The immutable ones are the easiest to use in programming (they are usually the simple data types: String, Integer, Boolean, others...) because they do exactly what they are expected to do at any given moment, and paradoxically, to function this way, they are the ones that most They punish memory (they are not optimized to take up less memory when copying, and they degrade memory life more by writing more times).
as we saw in the previous example or previous paragraph the lists if they are mutable but what happens if we try to modify a tuple class data structure in python what happens if we do this for example:
Clearly the tuples are immutable! We can not modify any of its elements since this will generate a similar type of error as in the previous example!
Let's Continue...
Let's go a code example a little more extensive and precise with the tuples like the following code, here we write a function that adds two tuples with a prototype equal to: (def add_tuple (tuple_a = (), tuple_b ()) :), its conditions are as follows:
- The first element must be the sum of the first element of each argument.
- The second element must be the addition of the second element of each argument.
- We assume that the two tuples will only contain integers
- If a tuple is less than 2, we will use the value 0 for each missing integer
- If a tuple is greater than 2, we will use only the first 2 integers
This is the result in code:
and this would be his exit:
In the previous example we have made an operation with the tuples the fact that they are immutable does not mean that we cannot manipulate them!
NOTE:
And exactly what is immutability in the programming context ...
The idea is very simple to understand: something is immutable when it cannot be modified. In the programming context, a variable is immutable when its value cannot be modified. And an object is when its state cannot be updated after the creation of the object. It is therefore a way of guaranteeing that our object does not change in unexpected places, thereby affecting the execution of our program.
Why does it matter and how differently does Python treat mutable and immutable objects
Until now every time we study a type of indicative variables if they are mutable or immutable. When a variable is of an immutable type, such as a string, it is possible to assign a new value to that variable, but it is not possible to modify its content.
This is because when a new assignment is made, the string itself is not modified, but the variable a starts to point to another string. Instead, it is not possible to assign a new character in a position, since this would imply modifying the immutable string.
In the case of mutable parameters, the assignment has the same behavior, that is, the variables point to a new value. with this example:
We write a function that replaces an element of a list at a specific position (like in C).
with the following prototype and the following conditions:
- Prototype: def replace_in_list(my_list, idx, element):
- If idx is negative, the function should not modify anything, and returns the original list
- If idx is out of range (> of number of element in my_list), the function should not modify anything, and returns the original list
In code it would look like this:
Your Output:
In the previous example we see in our codes lists mutable objects! What of course has their respective methods and how can we know all the methods of an object as special as a data structure? ... simple with the dir () method would be like this:
the methods we used in the previous example were:
- pop: his method deletes the element at the position mentioned in its arguments.
- len: returns the number of items listed
- insert: This function inserts an element at the position mentioned in its arguments. It takes 2 arguments, position and element to be added at respective position.
- index: Index returns the index number of the element that we pass to it by parameter.
Finally we will see the following:
How arguments are passed to functions and what does that imply for mutable and immutable objects:
Functions receive parameters that can be mutable or immutable. If one of these parameters is modified within the body of the function so that it points to another value, this change will not be reflected outside the function. If, on the other hand, the content of any of the mutable parameters is modified, this change will be reflected outside the function.
The following is an example in which the received variable is assigned to a new value. That assignment only takes effect within the function.
OUTPUT:
Final note: Since in this case the variables are lists (mutable objects), the function modifies the list that is sent as an argument: first the list "a" is modified and then the list "b". The modified list does not depend on the name of the parameter in the function (which is "b"), but on the variable sent as argument ("a" or "b")... (In general, it is expected that a function that receives mutable parameters will not modify them, since if they are modified, valuable information could be lost. In the event that the parameters received are modified by a design or specification decision, this must be clearly documented, within the post-conditions.)
I HOPE YOU WOULD HAVE ENJOYED THIS ARTICLE!