List methods and their cost

A list stores its items side by side in memory. That makes some methods cheap and others expensive:

  • append(x) and pop() work at the end: O(1).
  • insert(0, x) and pop(0) work at the front, so every other item has to shift over: O(n).
  • x in xs, xs.index(x) and xs.remove(x) search from the start: O(n). remove deletes only the first match.

Interviewers watch for pop(0) in a loop, for example when someone uses a list as a queue. Each call is O(n), so the loop is O(n²). The fix is collections.deque, which you will meet in the Batteries included chapter.

Run the code to compare building a list with append and with insert(0, x). Then double n and see which time grows faster.