Skip to the solution
MediumDSA5 min read

How does the bisect module work?

473 views

The problem

Question presented to candidate: "Say you have a big sorted list and you need to find where a value belongs, or count how many values fall in a range. What does Python's bisect module do, how does it work, and when is it the wrong tool?"

What a strong answer should cover:

  • bisect is binary search on an already sorted sequence: it halves a [lo, hi) window each step, so it needs about log2(n) comparisons (20 for a million items).
  • bisect_left returns the first position where x could go (before equal items), bisect_right / bisect the position after equal items; right - left counts the copies of x.
  • insort / insort_left / insort_right keep a list sorted, but the search is O(log n) while the list insert is O(n), so it does not beat a heap or a sorted container for many inserts.
  • The key= argument (added in Python 3.10) is applied to the list items, not to x; lo and hi limit the window; only < is used for comparisons.
  • Typical uses: membership in a sorted list, range counts, bucketing a score into a grade, and keeping a small sorted list up to date.

Code / implementation expected: Yes β€” either use bisect for a lookup/range task, or write bisect_left by hand.

  • bisect
  • binary-search

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonbisect_left, bisect_right, insort and key= in practice
PythonBinary search by hand, traced and counted

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 87 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

Why does Python cache small integers?

Continue