The statement a = a + " " + b + " " + c
can be broken down based upon pointers.
a + " "
says give me what a
points to, which can't be changed, and add " "
to my current working set.
memory:
working_set = "Dog "
a = "Dog"
b = "eats"
c = "treats"
+ b
says give me what b
points to, which can't be changed, and add it to current working set.
memory:
working_set = "Dog eats"
a = "Dog"
b = "eats"
c = "treats"
+ " " + c
says add " "
to the current set. Then give me what c
points to, which can't be changed, and add it to current working set.
memory:
working_set = "Dog eats treats"
a = "Dog"
b = "eats"
c = "treats"
Finally, a =
says set my pointer to point to the resulting set.
memory:
a = "Dog eats treats"
b = "eats"
c = "treats"
"Dog"
is reclaimed, because no more pointers connect to it's chunk of memory. We never modified the memory section "Dog"
resided in, which is what is meant by immutable. However, we can change which labels, if any, point to that section of memory.
id()
function.a
will have a different id before and after the assignment, indicating that it is pointing at different objects. Likewise with code likeb = a
you'll find thata
andb
will have the same id, indicating they're referencing the same object. – Scrutatora = []; a += [1]
mutates the list (not just the variable) buta = 'x'; a += 'y'
is still valid code. xD – Beauchamp