The bisect Module

The bisect module provides functions to insert items in sorted sequences.

insort(sequence, item) inserts an item into the sequence, keeping it sorted. The sequence can be any mutable sequence object that implements _ _getitem_ _ and insert; Example 14-28 demonstrates.

Example 14-28. Using the bisect Module to Insert Items in an Ordered List

File: bisect-example-1.py

import bisect

list = [10, 20, 30]

bisect.insort(list, 25)
bisect.insort(list, 15)

print list

[10, 15, 20, 25, 30]

In Example 14-29, bisect(sequence, item) => index returns the index where the item should be inserted. The sequence is not modified.

Example 14-29. Using the bisect Module to Find Insertion Points

File: bisect-example-2.py

import bisect

list = [10, 20, 30]

print list
print bisect.bisect(list, 25)
print bisect.bisect(list, 15)

[10, 20, 30]
2
1

Get Python Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.