Lesson · Useful Standard Library Collections
bisect
55 min readbisect
`bisect` locates insertion points in sorted lists using binary search. Search is logarithmic, but list insertion still costs linear time because later elements must move.
Learning goals
- Use
bisect_leftandbisect_rightto locate where a value belongs in a sorted list without scanning it. - Explain how the two functions differ when the list already contains equal values.
- Use
insortto add a value while keeping the list sorted. - State why locating the position costs a handful of comparisons while the insertion still moves many elements.
- Recognize the sorted precondition and predict what
bisectreturns when it is violated.
Mental model
The search half answers a position question with binary search; the insertion half pays for keeping the order. Because the second half shifts every element after the index, bisect is cheap when reads dominate writes and wrong for a list that changes constantly.
Mental model
read it top to bottom
sorted list ↓ bisect_left / bisect_right: where does x belong? insertion index (before the ties, or after them) ↓ insort: insert at that index sorted list, one element larger
Core idea
bisect exploits an existing order: with a sorted list, a handful of comparisons locates the exact index where a value belongs, which is why membership and range questions become position lookups. The asymmetry to keep in view is that finding the position is logarithmic while inserting there is linear, because every element after the index shifts.
bisect_left
bisect_left returns the insertion point before existing equal values. It performs binary search without inserting anything.
bisect_right
bisect_right returns an insertion point after existing equal values in a sorted list. It never mutates the list; together with bisect_left it brackets the run of equal values already present.
Maintaining sorted lists
Keeping a list sorted while adding to it means calling insort instead of append, so every element lands at the position bisect computes and the order never breaks. The payoff is that later membership and range checks can binary search instead of scanning; the cost is the shift after each insertion.
Search vs insertion cost
Binary search can find an insertion point in logarithmic comparisons, but inserting into a Python list still shifts later references and therefore costs linear time.
Walkthrough
bisect_left(scores, 25)returns2: the algorithm halves the search window until it collapses, and the index is where25would sit between20and30. Nothing is inserted and nothing is mutated.insort(scores, 25)searches for the same position and then inserts, so the list becomes[10, 20, 25, 30, 40]; the call returnsNone, and the shift of30and40is the linear part of the operation.- With duplicates the two search functions disagree:
bisect_leftreturns the index before existing equal values andbisect_rightthe index after them, which lets you choose which side of a tie a new value lands on. - Predict before running: what
positionprints, whereinsortplaces25, and what changes if the list already contained two values of25.
Experiments to try
- Build
scores = [10, 20, 20, 20, 30]and comparebisect_left(scores, 20)withbisect_right(scores, 20); state what the two indexes bracket. - Call
bisect_left([30, 10, 20], 15)on the unsorted list, record the returned index, and explain why the answer satisfies no meaningful question about the list. - Call
insorton a tuple and read theAttributeError; explain which part of the operation requires a mutable sequence. - Use
bisect_leftwithkey=lambda pair: pair[0]on a list of(score, name)pairs; note that the search value is a bare score becausekeyapplies to the list elements, not to the value being located.
Common mistakes
- Binary searching data that is not sorted:
bisectnever checks the precondition, so an unsorted list yields a confident-looking index that means nothing; sort the list first or maintain the order as it is built. - Mixing up
bisect_leftandbisect_rightaround duplicates: both return an index into the same list, but one lands before the run of equal values and one after, so the choice decides where new ties are placed. - Expecting
insortto inherit only the logarithmic cost of the search inside it: the comparisons are logarithmic, but moving the tail of the list is linear, so insertingnitems one at a time performs quadratic element movement. - Assuming
insortreturns the new list or the index: it mutates the list in place and returnsNone, and it needs a mutable sequence, so tuples fail withAttributeError.
Practice: Easy
- Run the worked example and print
scoresafter each line; note which call changed the list and which one only returned a number. - Compute
bisect_left(scores, 45)andbisect_right(scores, 45)on[10, 20, 30, 40]; both returnlen(scores), so explain what an insertion point past the end means. - Build
[10, 20, 20, 20, 30]and print both bisect variants for20; state what the two indexes bracket.
Practice: Medium
- Write
grade(score)that usesbisect_rightover the boundary list[60, 70, 80, 90]to pick a letter, then test it at 59, 60, 90, and 100 and explain the indexing. - Insert 5,000 random integers into a list one at a time with
insortand time the loop; then generate the same numbers again, sort once, and time that; account for the difference with the linear shift. - Use
key=lambda pair: pair[0]to locate where a score of 75 would enter a sorted list of(score, name)pairs, and explain why the search value is75and not a tuple.
Practice: Hard
- Design a leaderboard that keeps entries sorted by score with
insort: supportadd(score, name),rank_of(score)for the first index of a score, andcount_at(score)using the two bisect variants; define the behavior for scores that are absent. - Failure lab: trigger three traps, a search on unsorted data returning a plausible index, an
insorton a tuple raisingAttributeError, and a duplicate landing differently underinsort_leftversusinsort_right; explain each mechanism. - Connect this lesson to the performance module: design a measurement that finds the list size where maintaining order with
insortstops beating sort-on-demand for a workload with many reads and few writes.
Lesson checklist
- I can find the insertion point for a missing value with
bisect_leftorbisect_right. - I can explain what the two functions return around a run of duplicates.
- I can use
insortto add a value and keep the list sorted, and say why it returnsNone. - I can state why the position search is logarithmic but the insertion is linear.
Remember
`bisect` turns a sorted list into a searchable index: `bisect_left` and `bisect_right` report where a value belongs, before or after equal values, and `insort` performs that insertion so the order survives. Finding the index costs a few comparisons while inserting moves elements, so reach for `bisect` when reads dominate writes.
Interview angles
What is the main purpose of **bisect_left**?+
bisect_left returns the insertion point before existing equal values. It performs binary search without inserting anything.
What should you pay attention to when using **bisect_right**?+
bisect_right returns the index after any existing equal values, so it marks the far edge of a run of duplicates. Paired with bisect_left, the two indexes bracket every existing copy of the value, and neither call mutates the list.
How does **Maintaining sorted lists** fit into this lesson?+
Maintaining a sorted list means calling insort instead of append, so every addition lands at the position bisect computes and the order never breaks. That keeps binary search valid for later reads, at the price of the linear shift after each insertion.
Why does `bisect_left([30, 10, 20], 15)` return 2 instead of failing on the unsorted input?+
bisect assumes sorted order and never verifies it; it halves the unsorted list and returns the index where its window collapsed, so the number is an artifact of the comparisons rather than a real insertion point. Sort the list first or keep it sorted with insort.