Strings as immutable sequences (why in-place edits aren't free)
standardbeginnerA Python string cannot be changed in place — s[0] = 'x' raises an error. Any 'edit' actually builds a brand-new string, which is why string-building patterns matter (§2's O(n²) `+=` trap comes directly from this).
Think of it as
A string behaves like a tuple of characters: indexable and iterable, but frozen once created. 'Editing' one character really means constructing an entirely new string that differs by one character — there is no operation that changes a string's existing memory in place.
What we're doing: Confirm that direct item assignment on a string fails, and show the correct way to change one character.
- 3
- Item assignment is simply not defined for str — this raises immediately, rather than silently doing nothing.
TypeError 'str' object does not support item assignment
batWhy this works: The TypeError confirms strings have no in-place mutation at all — the only way to 'change' one character is to build a new string (here, the first character replaced, the rest sliced and reused) and rebind the name to it.
Remember: A string can never be edited in place — every apparent edit builds an entirely new string, which is the root cause of §2's O(n²) `+=`-in-a-loop trap.
See also: string concat o n squared

