Everything is an object in python
Introduction
Objects can be defined simply as the instance of a class that contains both data members and method functions. All data in a Python program is represented by objects or by relationships between objects. Booleans, integers, floats, strings, data structures, program functions... they are all implemented as an object.
id() and type()
As we said before, everything is an object and these have a type and an id, the type of an object can be obtained through the type() function:
With the id function we can obtain an integer that is the identifier of that object, this id is unique and represents it in memory:
Mutable and immutable objects
Python has a quirk and treats its data types as mutable or immutable, which means that if the value can change, the object is called mutable, while if the value can't change, the object is called immutable.
mutable: Mutable object values can be changed anytime, anywhere after creation:
- Lists
- Sets
- Dictionaries.
Immutable: That a type is immutable means that it cannot be changed after it has been created.
- int
- float
- String
- Tuples
This happens because we are trying to change the value of an immutable object, since the strings in Python are immutable.
It seems that we are changing the string, but in reality what we are doing is assigning it a new value, since if you realize it, we are passing the = sign and the new value that we want that variable to have.
Why does it matter and how differently does Python treat mutable and immutable objects?
Python handles mutable and immutable objects differently. Immutables are faster to access than mutable objects. Also, immutable objects are fundamentally expensive to “change”, because doing so involves creating a copy. Changing mutable objects is cheap.
Mutable objects are very good when you need to resize the object, i.e. it will be dynamically modified
How arguments are passed to functions and what does that imply for mutable and immutable objects?
When an immutable object is passed as an argument to a function, it is passed as a value, we know that as immutable objects, they cannot be modified. So no matter what happens in the function, the values are not going to be modified directly.
On the other hand, when the arguments are mutable objects, they are passed as a reference to the objects and can be modified by the function. So if we pass a list to a function, the values of the list can be modified by the function itself.
Knowing this, we have to be careful because if, for example, we do not want to modify the original list that we pass to the function, we must create a copy of the list within it. That way, we'll have a new memory address and a new list as a local variable.