Python3: Mutable, Immutable… everything is object!
Do you know everything in python is an object? In this article you will learn about id and type along with the different types of objects, which can be either mutable or immutable.
ID AND TYPE
Here we will start by knowing the memory address of an object (which can be a method or variable). The id() function get us the memory address of our instance created, an example would be this:
- id is a built-in function in python that returns a unique id (identifier) for the specific object, which is the address of the object in memory.
- The type() function shows the type of the argument passed between the parenthesis. For example:
The example is telling us that:
- (123) is of type integer
- (“Hello World”) is of type string
- (1.123) is of type float
MUTABLE OBJECTS IN PYTHON
In a brief way mutable objects can be manipulate without having to create a new instance, this data structures are list, dict and set. Mutable objects value can be freely modified after it is created.
- In the previous example we can see that we are modifying a type list in position zero(0), from the integer 1 to integer 8.
Immutable objects are usually the simple data types such as : String, Integer, Boolean, etc. They are in fact objects that can’t be freely changed after their creation. Let’s see an example of a immutable object instead of mutable:
- As we can see in the previous example, tuples are clearly immutable. We can’t modify any of its elements since this will generate a similar type of error as in the previous example.
- But, lets see this example string1 = string1 + string2:
Where we will concatenate two strings in the same variable name (looking like if we’re modifying a immutable object), but lets see the example below:
- As you can see with id we can verify that str1 have different memory addresses before and after being concatenate.
Why does it matter and how differently does Python treat mutable and immutable objects
When we make a new assignment the string itself is not modified, but the variable ‘a’ starts to point to another string. It is not possible to assign a new character in a position, since this would imply modifying the immutable string, as shown in the follow example:
- As you can see it is possible to assign a new value to the variable, but it is not possible to modify its content. This is for the fact that when a new assignment is made the string is not modified, but the variable ‘a’ starts to point to another string.
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 parameter in the body of the function is modified to point to another value, the change will not be reflected outside the function. But, if the content of any of the mutable parameters is modified, then it will be reflected outside the function.