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?
First
a
pointed to the string "Dog". Then you changed the variablea
to point at a new string "Dog eats treats". You didn't actually mutate the string "Dog". Strings are immutable, variables can point at whatever they want.The variable a is pointing at the object "Dog". It's best to think of the variable in Python as a tag. You can move the tag to different objects which is what you did when you changed
a = "dog"
toa = "dog eats treats"
.However, immutability refers to the object, not the tag.
If you tried
a[1] = 'z'
to make"dog"
into"dzg"
, you would get the error:because strings don't support item assignment, thus they are immutable.
Consider this addition to your example
One of the more precise explanations I found in a blog is:
Link to blog: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/
Summarizing:
Not immutable:
Immutable:
This is an error in Python 3 because it is immutable. And not an error in Python 2 because clearly it is not immutable.
There is a difference between data and the label it is associated with. For example when you do
the data
"dog"
is created and put under the labela
. The label can change but what is in the memory won't. The data"dog"
will still exist in memory (until the garbage collector deletes it) after you doIn your programm
a
now ^points to^"cat"
but the string"dog"
hasn't changed.