Why is `"".join(parts)` recommended over repeated `+=` concatenation when building a large string from many pieces?
Answer
Because strings are immutable, each `result += piece` in a loop conceptually must allocate a new string and copy the old content plus the new piece into it, which makes naive repeated concatenation an O(n²) pattern for n pieces in the general case. `"".join(parts)` first walks the list once to compute the total length, allocates a single buffer of exactly that size, and copies each piece into it once, making the whole operation O(n). In practice, CPython has an internal optimization that can sometimes extend a string in place when a loop variable holds the only reference to it, but that optimization is a CPython implementation detail rather than a language guarantee, so `"".join()` remains the predictable, recommended approach whenever you are combining many pieces.
Strong answer includes
- loop += naively reallocates and copies each iteration, O(n squared) in the general case
- join precomputes total length and allocates once
- CPython's in-place-extend optimization is an implementation detail, not a language guarantee — join stays the predictable choice
Practical example
Building a 100,000-line report with
report += linein a loop is measurably slower than collecting lines into a list and calling
"\n".join(lines)once at the end.