How to Use bisect.insort in Python to Maintain a Sorted List

Insert items into an already sorted list using Python's bisect.insort to keep it sorted efficiently in O(n) time.

Easy Python 3.9+ Aug 9, 2026 Concurrency & performance 13 views 0 copies

Python code

21 lines
Python 3.9+
import bisect

def maintain_sorted_list():
    data = [3, 1, 4, 1, 5, 9, 2, 6]
    sorted_list = []
    
    for num in data:
        bisect.insort(sorted_list, num)
    
    print("Original data:", data)
    print("Sorted list maintained with insort:", sorted_list)
    
    # Insert new values to maintain sorted order
    bisect.insort(sorted_list, 7)
    bisect.insort(sorted_list, 0)
    bisect.insort(sorted_list, 5)
    
    print("After inserting 7, 0, and 5:", sorted_list)

if __name__ == "__main__":
    maintain_sorted_list()

Output

stdout
Original data: [3, 1, 4, 1, 5, 9, 2, 6]
Sorted list maintained with insort: [1, 1, 2, 3, 4, 5, 6, 9]
After inserting 7, 0, and 5: [0, 1, 1, 2, 3, 4, 5, 5, 6, 7, 9]

How it works

The bisect module implements a binary search to find the correct insertion point for each new value in O(log n) time. bisect.insort (an alias for insort_right) inserts the item at that position while shifting existing elements to the right, resulting in an O(n) insertion due to list shifting. This is ideal when the list is already sorted and you need to insert many elements without re-sorting the entire list each time. The insort function adds duplicates to the right of equal values, preserving the sort order.

Common mistakes

  • Using `bisect.insort` on an unsorted list, which produces incorrect ordering.
  • Forgetting that `insort` modifies the list in place, so it should not be relied upon to return the list.
  • Assuming O(1) insertion time; the shift is still O(n) and may be slower than using `bisect` only when the list is huge.

Variations

  1. Use `bisect.insort_left` to insert duplicates to the left of existing equal values.
  2. For many insertions, consider using a `heapq` heap, though it doesn't maintain sorted order directly.

Real-world use cases

  • Maintaining a leaderboard in sorted order as new scores stream in from many players.
  • Keeping a list of events sorted by timestamp while continuously adding new log entries.
  • Building a dynamic priority queue where order is based on a numeric key and insertions happen frequently.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Concurrency & performance

Related tutorials and quizzes for this topic.