Why are Python strings immutable, and what does that mean for methods like `.upper()` or `.replace()`?
Answer
Strings are immutable so they can be hashed safely and shared efficiently between variables without defensive copying, and so that once created, a string's content can never be silently changed by code elsewhere holding the same reference. Every string method that looks like it "changes" a string, such as `.upper()`, `.replace()` or `.strip()`, never mutates the original string in place — it returns a string holding the result, and the original's content is only affected if you reassign the variable to that new result. (Whether the returned object happens to be freshly allocated or, in edge cases like a no-op transform, the very same object, is an implementation detail Python does not guarantee either way — the only guarantee is that the original is never mutated.)
Strong answer includes
- immutability enables safe hashing and sharing
- string methods never mutate the original, they return a result instead
- original unaffected unless reassigned
Practical example
name = "ann"; name.upper()evaluates to `"ANN"` but leaves `name` still equal to `"ann"` unless you write
name = name.upper().