ProgrammingHardAmazon OA · Flipkart coding round

Which loop builds a list of n items in total O(n^2) time in CPython, because each step copies the whole list?

  1. A. lst.extend([x]) inside the loop
  2. B. lst += [x] inside the loop
  3. C. lst = lst + [x] inside the loop, which creates a new list every step
  4. D. lst.append(x) inside the loop

Correct answer: C. lst = lst + [x] inside the loop, which creates a new list every step

lst = lst + [x] builds a new list with all previous items each time, so the copying adds up to about n^2 / 2 element copies. append and += on a list extend it in place, which is amortised O(1) per item.

More Python Programming questions

Exams that ask this topic