Mutable or immutable? That is the question
A first fundamental distinction that Python makes on data is about whether or not the value of an object changes. If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.
It is very important that you understand the distinction between mutable and immutable because it affects the code you write, so here's a question:
In the preceding code, on the line #A
, have I changed the value of age? Well, no. But now it's 43 (I hear you say...). Yes, it's 43, but 42 was an integer number, of the type int
, which is immutable. So, what happened is really that on the first line, age
is a name that is set to point to an int
object, whose value is 42. When we type age = 43
, what happens is that another object is created, of the type int
and value 43 (also, the id
will be different), and the name age...