ProgrammingHardProduct-company MCQ pattern

Which of these is the best way to build a string from n pieces in CPython, and why?

  1. A. Repeated s += piece, because CPython always resizes the string in place so the total cost is O(n)
  2. B. Repeated s = ''.join([s, piece]), because join is O(1) amortized
  3. C. Repeated str.format calls inside the loop, because format avoids copying the existing string
  4. D. Collecting the pieces in a list and calling ''.join(pieces) once, because it copies each piece once for O(total length)

Correct answer: D. Collecting the pieces in a list and calling ''.join(pieces) once, because it copies each piece once for O(total length)

join computes the total length first and copies each piece once, so the total work is linear in the output length. Repeated += copies the existing text each time unless CPython's in-place optimisation applies, and that optimisation is an implementation detail, not a guarantee.

More Python Programming questions

Exams that ask this topic