34/41
Part 7 of 7 · Follow-upsLearn

How do you keep a list sorted while it changes?

insort is O(n) per insert: the insort step measured 229.81 µs for an insort and a removal on a million items. That's fine for a few inserts, and wrong for a stream of them:

  • When you only need the smallest, use a heap. It hands back its smallest item and takes a new one in O(log n), and the next lesson builds one.
  • When you need order, ranks and deletes from the middle, use a balanced search tree, O(log n) for each. Python's standard library doesn't have one. The third-party sortedcontainers package provides a SortedList for that job.
  • When all the items arrive before the first question, append them and sort once: 12.9 ms against 484.0 ms for 100,000.