🐍 Python Advanced

What is Python's bisect module?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

The bisect module provides binary search functions for maintaining sorted lists in O(log n) time. bisect.bisect_left(lst, x) — returns the leftmost position where x can be inserted to keep the list sorted (elements equal to x go to the right of this position). bisect.bisect_right(lst, x) (same as bisect.bisect()) — returns the rightmost insertion point. bisect.insort_left(lst, x) — inserts x at the correct position (O(log n) search but O(n) insert due to list shifting). Example — grade classification: def grade(score): return "ABCDF"[bisect.bisect([60, 70, 80, 90], score)]. Finding the rank of a value in a sorted list: rank = bisect.bisect_left(sorted_list, value). Use bisect when you have a sorted list and frequently need to find positions or insert values while maintaining order. For frequent insertions, sortedcontainers.SortedList is more efficient.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Python project, I used this when...' immediately makes your answer more credible and memorable.