Python's Bisect Method

In this lesson, you will learn about the bisect module in Python.

In this lesson, we will learn about a function that takes an array of sorted integers and a key and returns the index of the first occurrence of that key from the array.

For example, for the array:

[-14, -10, 2, 108, 108, 243, 285, 285, 285, 401]

with

target = 108

the function would return 3, as the first occurrence of 108 in the above array is located at index 3.

We introduce to you: the bisect module in Python! Bisect is a built-in binary search method in Python. It can be used to search for an element in a sorted list. Let’s see how we make use of different methods provided by the bisect module.

bisect_left()

The bisect_left function finds the index of the target element. In the event where duplicate entries are satisfying the target element, the bisect_left function returns the left-most occurrence. The input parameters to the method are the sorted list and the target element to be searched.

Have a look at the examples below:

Get hands-on with 1200+ tech skills courses.