insort
insort inserts into a sorted list while keeping it sorted. Finding the spot is O(log n), but the list shift makes each insert O(n), so it's fine for small or read-heavy data; for heavy insert/delete workloads use a heap or sortedcontainers.SortedList.
Syntax
from bisect import insort
a = [1, 3, 5]
insort(a, 4) # a -> [1, 3, 4, 5], O(log n) search + O(n) shift
insort_left vs insort_right
from bisect import insort_left, insort_right
a = [(1, "x")]
insort_left(a, (1, "a")) # equal keys: goes before existing equal items
insort_right(a, (1, "z")) # equal keys: goes after (insort == insort_right)
a # -> [(1, 'a'), (1, 'x'), (1, 'z')]
Keep a running sorted list
from bisect import insort, bisect_left
window: list[int] = []
for x in [5, 2, 8, 1]:
insort(window, x)
window # -> [1, 2, 5, 8]
window.pop(bisect_left(window, 5)) # remove a value, O(n)
window # -> [1, 2, 8]
mid = window[len(window) // 2] # median lookup O(1)
key= (3.10+)
from bisect import insort
events = [(1, "start"), (5, "end")]
insort(events, (3, "mid"), key=lambda e: e[0])
events # -> [(1, 'start'), (3, 'mid'), (5, 'end')]
# Unlike bisect_*, insort passes the whole item and applies key to it
Complexity cheat
# insort: O(n) per insert (O(log n) search + O(n) shift)
# n inserts: O(n^2) worst case; fine up to roughly 10^4-10^5
# heapq push/pop: O(log n), but only the min is accessible
# SortedList (3rd-party, often allowed on LeetCode): O(log n) add/remove/index