Python and Objects
In this post we will talk about mutable and immutable objects in python, how does python treat them differently how you pass arguments to function and what does that imply for mutable and immutable objects, also we will see the id and type of objects.
Type of an object
Objects have a type that defines the possible values and operations that type supports. The type of an object is unchangeable like the ID, if we want to see the type of an object we can just use the type() funtion, let’s see an example
>>> a = 10
>>> type(a)
<class 'int'>
>>> food = "banana"
>>> type(food)
<class 'str'>
ID of an object
Every object in python have a “identity” this identity is an integer that is guaranteed to be unique and constant during the lifetime of the object. Two objects with non-overlapping lifetimes may have the same identity value , in CPython implementation this is the adress of the object in memory.
Let’s take a view to some examples:
#Integers
a = 10
b = 2
c = 6
d = 10print(id(a))
print(id(b))
print(id(c))
print(id(d))
The output could be something like:
10105376
10105120
10105248
10105376
Notice that the identity of ‘a’ and ‘d’ are the same, but why? well, we know they both have the same value, but the reason of that is because they are pointing to the same object, we can see an example:
>>> a = 12
>>> b = 12
>>> a is b
True
Mutable and Immutable objects
Once the ID and the type of an object is created it never changes, it is used behind the scenes by Python to retrieve the object when we want to use it. The value can change or not, if it can it is called Mutable object, if not it is called Immutable object.
Some of the more common mutable objects are: list, dictionaries, sets and usser-defined classes
More common immutable objects are: int, floats and decimals for numbers, we also have strings, tuples and range
Now let’s take a peak into some examples
age = 20
print(id(age))
print(type(age))
print(age)age = 18
print(id(age))
print(age)
The output will be
10106400
<class 'int'>
20
10106432
18
Did the value of “age” change? Nop, when we typed “age = 18” we just created a new object of type int, value 18 and a new identity value, so we didn’t actually change 20 to 18 we just pointed “age” to a new object
Now let’s see a mutable object
list_name = [3, 6, 9, 12]
print(list_name)
print(id(list_name))list_name.pop()
print(list_name)
print(id(list_name))
The output will be something like this:
[3, 6, 9, 12]
140363239712584
[3, 6, 9]
140363239712584
We created a list that contains 4 integers, when we popped the last value the identity of the list is the same, that’s a mutable object.
I hope you liked it, have a good coding :D