Building a large string with s += piece in a loop is discouraged because…
Options
- Strings are mutable, so they can get corrupted in a loop
- It can be quadratic, since each
+=may copy the whole string (Correct option) - It raises a MemoryError once the string passes 1 MB
- f-strings are required for any string longer than a line
Answer
It can be quadratic because each += may copy the whole string
Why
Strings cannot be changed (they are immutable). So s += piece builds a brand-new string and copies all the old characters every time.
With many pieces this gets very slow (time grows with the square of the size).
Collect the pieces in a list and join them once at the end.
parts = []
for row in rows:
parts.append(str(row))
text = "".join(parts)Remember
Build big strings with "".join(list).