Python: Objects, mutable and Immutable
In python there are diferents types of objects, each with its own characteristics. This objects can be mutable or immutable and it is very important to understand the difference between these, in order to use them correctly. in this blogpost i will talk about them.
Id and Type
The objects in python have a particular and unique id, to obtain it we must use the id() function, in this way we can identify them. The objects can also be of different types for example int, float, list, tuple, etc. To get it we use the type() function. The id and type of an object is assigned when it is created and will never change
Mutable and Immutable objects
Mutable objects are those that can be changed after they have been created, there are list, dict, set, bytearray. On the other hand, immutable objects are those that cannot be changed after being created, there can be, number (int, float, complex), string, tuple, frozen set, bytes. When we use a mutable object in a function, any changes that the object receives will stay, but when the object is immutable the changes will not persist after the function returns.
Differentiating these objects is important, as it affects how memory is treated. When a mutable object is assigned, the variable refers to the object in the memory, if it changes the changes are also reflected in the variable, instead if it is immutable, the variable refers to a new object in memory and if the object original changes the variable is not affected.
领英推荐
NSMALLPOSINTS and NSMALLNEGINTS
When we start the execution of CPython a limited number of integers are pre-allocated (the first 262 integers), these are NSMALLPOSINTS and NSMALLNEGINTS. These entries are the most used and serve to improve the performance of the application, because they can be quickly accessed and reused without having to create a new object each time.
Alias
The concept of aliases is another to take into account, they are names that we assign to refer to a particular object. These alias can be created for all objects, but when we assign it to an immutable object, the aliases will not be able to modify the value of the object.
Tuple and Frozen Set
Finally we have the case of tuples and frozen sets, these are immutable objects, once created they cannot add, delete or change, but within them they can contain mutable objects.