10/30
Part 3 of 7 · Two sorted listsLearn and do

bisect.insort files a key in its place

A list stays sorted only if every key goes in at the right spot. The bisect module finds that spot by binary search:

from bisect import bisect_left, insort

WAITING = [(-9, "Comet"), (-7, "Harbor"), (-7, "Maple"), (-5, "Orbit"), (-3, "Tundra")]
print(bisect_left(WAITING, (-7, "Maple")))
print(bisect_left(WAITING, (-8, "Maple")))
2
1

bisect_left(keys, key) returns the index where key would go to keep the list sorted. If the key is in the list, that's its index: (-7, 'Maple') is at 2. If it isn't, you still get a number. (-8, 'Maple') would go at 1, where Harbor sits. So after bisect_left, check keys[i] == key before you trust the index, and check i < len(keys) first, because a key past the end gives len(keys).

insort(keys, key) does the search and then inserts. The search is O(log n), and the insert shifts every later key one place, which is O(n). The bisect docs say plainly that the slow insertion step dominates. In practice the shift is a fast memory copy in C: at 100,000 titles, a delete plus an insert measured about 20 µs.

The editor holds add and find over a sorted list of keys. Write add(keys, title, score) with insort, and find(keys, title, score) with bisect_left, returning -1 when the key isn't there.