Have you ever wanted to:

1. Find the position in a sorted array where a new element should be inserted

2. Insert an element in to a sorted array and maintain sort order

If yes, then this is for you.

The Bisect module allows you to search for an insertion point in a sorted array and as an extension of that to insert the element and maintain sorted order. The keyword being that the array is already sorted in some order.

The official docs are here

The source code is here

The following methods are defined in the module:

bisect.bisect_left(a, x, lo=0, hi=len(a))
bisect.bisect_right(a, x, lo=0, hi=len(a))
bisect.bisect(a, x, lo=0, hi=len(a))
bisect.insort_left(a, x, lo=0, hi=len(a))
bisect.insort_right(a, x, lo=0, hi=len(a))
bisect.insort(a, x, lo=0, hi=len(a))

Now, lets see some simple examples to illustrate the methods. Lets consider the case where an element is already present:

>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> bisect.bisect_left(l, 5)

5

>>> bisect.bisect_right(l, 5)

6

>>> bisect.bisect(l, 5)

6

As you could see above, bisect is similar to bisect_left but bisect returns an insertion point which comes after (to the right of) any existing entries of 5 in l. In essence bisect and bisect_right are equivalent. You could see that in the source code here at Line 79.

#python #python3 #bisect #python-programming #array

Python — Bisect Module — Search and Insert into a Sorted Array
3.40 GEEK