Why are Python strings immutable?
Because a string's value can never change, its hash can never go stale and a reference to it can never be invalidated by someone else. That is what makes strings usable as dictionary keys and safe to share without copying. The cost is that every "modification" builds a new object.
Overview
What immutability actually means
There is no operation in Python that changes a string in place. s.upper(), s.replace(), s.strip() and s + t all return a new string and leave the original exactly as it was. Assigning to an index — s[0] = 'A' — is not slow, it is a TypeError.
This is enforced, not advisory. There is no private method and no escape hatch, which is what lets the interpreter make assumptions it could not otherwise make.
Step through it
What to watch
t = smakes no copy — both names point at one object.upper()returns a different object;sis untouched.- The stable hash at the end is the payoff, not a side effect.
Say this out loud
"Immutable means every operation returns a new string. It buys hashability - so strings can be dict keys - and it means sharing a string is free. It costs you concatenation in a loop, which is why you use join."