Consider the following code:
aa=2
bb=aa
aa=4
print(bb) # displays 2
list1=[0]
list2=list1
list1[0]=5
print(list2) # displays [5]
As we see, the behavior is different from the variable containing number and list. I know that in the case of the numbers, when I do:
aa=4
I am telling to Python to create a new memory slot and putting the integer 4 in it. So before this line, bb and aa were referring to the same memory slot but not anymore after this line. bb still refers to the original memory slot containing the value 2 and it is why it hasn't been "updated".
For the list on the other hand, everything is the same before the following line
list1[0]=5
But right after this line, the value contained in the memory slot where list1 and list2 both refers to is changed. This is why list2 will also be changed after.
My questions:
Is the notion of mutable/unmutable object exactly related to this behavior ? In practice, for any mutable object, the same kind of behavior as the one for the list here would occur: if I change the value of an object a, then all object that were assigned to it will also be updated. But for unmutable object, if I change the value of this object a, all other object that were assigned to it before will not have been updated or it is simply impossible to change the value of a at all (like for tuples for instance).
Second but very highly related question. What confused me is that while being unmutable, numbers can be "modified" in the sense that the following code works:
a=2
a=3
Even though I know in practice a new memory is created at the second line (and the first line creates "an orphan"), this is a kind of specific behavior. For tuples it is simply impossible to modify them. Is there a logic behind this "dissymetry" in the behavior depending on the kind of variable within the unmutable ones ?