How to Use bisect Module in Python for Sorted Lists
The
bisect module in Python helps you insert items into sorted lists while keeping them sorted. Use bisect.bisect() to find the insertion point and bisect.insort() to insert an element in the correct position.Syntax
The bisect module provides two main functions:
bisect.bisect(list, item, lo=0, hi=len(list)): Returns the position whereitemshould be inserted to keep the list sorted.bisect.insort(list, item, lo=0, hi=len(list)): Insertsiteminto the list at the correct position to maintain sorting.
Parameters lo and hi define the slice of the list to consider.
python
import bisect # bisect function syntax pos = bisect.bisect(sorted_list, item, lo=0, hi=len(sorted_list)) # insort function syntax bisect.insort(sorted_list, item, lo=0, hi=len(sorted_list))
Example
This example shows how to find the insertion point for a number in a sorted list and how to insert it while keeping the list sorted.
python
import bisect numbers = [10, 20, 30, 40, 50] # Find position to insert 35 pos = bisect.bisect(numbers, 35) print(f"Insert 35 at position: {pos}") # Insert 35 into the list bisect.insort(numbers, 35) print("List after insertion:", numbers)
Output
Insert 35 at position: 3
List after insertion: [10, 20, 30, 35, 40, 50]
Common Pitfalls
Common mistakes include:
- Using
bisecton unsorted lists, which gives incorrect results. - Confusing
bisect.bisect()(which returns insertion point) withbisect.insort()(which inserts the item). - Not specifying
loandhiwhen you want to limit the search range.
python
import bisect numbers = [10, 30, 20, 40, 50] # Not sorted pos = bisect.bisect(numbers, 25) print(f"Wrong position in unsorted list: {pos}") # Wrong result # Correct way: sort first numbers.sort() pos = bisect.bisect(numbers, 25) print(f"Correct position after sorting: {pos}")
Output
Wrong position in unsorted list: 2
Correct position after sorting: 2
Quick Reference
| Function | Purpose | Returns/Inserts |
|---|---|---|
| bisect.bisect(list, item, lo=0, hi=len(list)) | Find insertion point for item | Index position (int) |
| bisect.insort(list, item, lo=0, hi=len(list)) | Insert item into list | None (modifies list) |
Key Takeaways
Use bisect.bisect() to find where to insert an item in a sorted list without changing it.
Use bisect.insort() to insert an item into a sorted list while keeping it sorted.
Always ensure the list is sorted before using bisect functions to get correct results.
You can limit the search range with lo and hi parameters for efficiency.
bisect module is useful for maintaining sorted lists without full sorting after each insertion.