Python : String as immutable type

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

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:

because strings don’t support item assignment, thus they are immutable.