String immutability enables safe sharing and hashing; use join for repeated concatenation
Python strings are immutable so they can be safely shared, interned, hashed, and used as dict keys without defensive copying. Immutability also makes them thread-safe for readers. The performance cost is that each concatenation creates a new string and copies both operands. Doing s += part in a loop can become O(n^2) because the growing string is copied repeatedly. The standard fix is to collect parts in a list and call ''.join(parts) once, or use io.StringIO for streaming.
Use ''.join(parts) for a known set of chunks; it computes total length and copies once.
Use io.StringIO for incremental building when you cannot hold all parts or need file-like writes.
Trade-off: for a few small strings, + is fine and more readable. Optimize only when profiling shows string concatenation is hot.
Common mistake: assuming CPython always optimizes += in a loop. It may optimize some cases, but it is not guaranteed and breaks with references or different implementations.
Version note: f-strings, join, and StringIO are stable; CPython has had some local += optimizations, but do not rely on them.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience