Many of them moving from Java to Python get confused with the way Python string immutability work. I have put down a compilation of different example I found to help you understand the same.
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"
to a = "dog eats treats"
.
Example
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 # !!!
Question: Shouldn’t python prevented the assignment?
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"
to a = "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:
TypeError: 'str' object does not support item assignment"
because strings don’t support item assignment, thus they are immutable.