Skip to content

Python · performance

no-string-concat-in-loop

python:no-string-concat-in-loop

Do not grow one string with repeated concatenation inside a loop.

Code
SARJ002
Default
error
Fix
none
Languages
python

Why

Repeated string growth copies the accumulated value on each iteration and can take quadratic time.

Fix

Append each fragment to a list and join the fragments once after the loop.

Before / after

Executed by this rule’s unit tests.

Before

String accumulator grown on every iteration

app/render.py · focus
def render(items):
    result = ""
    for item in items:
        result += f"{item}\n"
    return result

After

Fragments joined after the loop

app/render.py · focus
def render(items):
    lines = []
    for item in items:
        lines.append(str(item))
    return "\n".join(lines)

Limits

  • The rule requires syntax that establishes string-like growth and excludes generated files.
  • Subscript targets, per-iteration reinitialization, and intermediate values consumed by the loop are excluded.

Formerly: inefficient-string-concat-in-loop