While looking for ways to keep a list sorted irrespective of insertions and deletions, I came across the bisect
and sortedcontainers
modules.
bisect
‘s insort
function is O(n)
since it combines bisect_left
O(log n)
and insert
O(n)
def insort_left(a, x, lo=0, hi=None, *, key=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the left of the leftmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
A custom key function can be supplied to customize the sort order.
"""
if key is None:
lo = bisect_left(a, x, lo, hi)
else:
lo = bisect_left(a, key(x), lo, hi, key=key)
a.insert(lo, x)
However, an equivalent operation add
for SortedList
from sortedcontainers
module is O(log n)
due to this reason.
Now as I understand, it was a design decision to not include sorted containers in Python’s standard libraries – Source.
So between this design decision meant for simplicity and SortedList
meant for performance, how is bisect
even relevant? Is there a use case where bisect
could be preferred?