Repaso
Español
PythonIntermediatePY-32

Building a large string with s += piece in a loop is discouraged because…

Options

  1. Strings are mutable, so they can get corrupted in a loop
  2. It can be quadratic, since each += may copy the whole string (Correct option)
  3. It raises a MemoryError once the string passes 1 MB
  4. 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).

Key terms

Practice this question in Repaso