String concat in loop (ARCH2070)
Key python.performance.string-concat-in-loop · Severity warning · Category performance
Strings are immutable, so accumulating with += in a loop builds a new copy each iteration, yielding O(n²) cost. Collect parts in a list and join once at the end.
Incorrect
Section titled “Incorrect”def render(items): out = "" for item in items: out += str(item) + "," return outCorrect
Section titled “Correct”def render(items): parts = [str(item) for item in items] return ",".join(parts) + "," if parts else ""Collect fragments in a list and combine them in one pass with "".join(...) after the loop.