My understanding was that Python strings are immutable.
I tried the following code:
a = "Dog"
b = "eats"
c = "treats"
print a, b, c
# Dog eats treats
print a + " " + b + " " + c
# Dog eats treats
print a
# Dog
a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!
Shouldn't Python have prevented the assignment? I am probably missing something.
Any idea?
A variable is just a label pointing to an object. The object is immutable, but you can make the label point to a completely different object if you want to.
Python strings are immutable. However,
a
is not a string: it is a variable with a string value. You can't mutate the string, but can change what value of the variable to a new string.The statement
a = a + " " + b + " " + c
can be broken down based upon pointers.a + " "
says give me whata
points to, which can't be changed, and add" "
to my current working set.memory:
+ b
says give me whatb
points to, which can't be changed, and add it to current working set.memory:
+ " " + c
says add" "
to the current set. Then give me whatc
points to, which can't be changed, and add it to current working set. memory:Finally,
a =
says set my pointer to point to the resulting set.memory:
"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.Consider:
Notice that the hex memory location did not change when I stored the same value in the variable twice. It did change when I stored a different value. The string is immutable. Not because of zealotry, but because you pay the performance penalty of creating a new object in memory. The variable
a
is just a label pointing to that memory address. It can be altered to point to anything.You can make a numpy array immutable and use the first element:
then:
or
Something is mutable only when we are able to change the values held in the memory location without changing the memory location itself.
The trick is: If you find that the memory location before and after the change are the same, it is mutable.
For example, list is mutable. How?
A string is immutable. How do we prove it?
we get
So we failed mutating the string. It means a string is immutable.
In you reassigning, you change the variable to point to a new location itself. Here you have not mutated the string, but mutating the variable itself. The following is what you are doing.
id
before and after reassignment is different, so it this proves that you are actually not mutating, but pointing the variable to new location. Which is not mutating that string, but mutating that variable.