What is the bisect.bisect() function in Python?

Overview

In Python, the bisect module in Python assists in preserving a list in sorted order after the insertion of a new element. This is because it bypasses the sort operation after each insertion.

The bisect() function of the bisect module returns the position where we can insert a new element by maintaining the sorted order.

Syntax

bisect.bisect(list, element,lo=0,hi=len(a))

Parameters

It takes four parameter values:

  • list: This is a sorted Python list.
  • element: This is the new element that we wish to add.
  • lo: This is the start index of the list subset. The default value of this parameter is 0. This is an optional parameter value.
  • hi: This is the end index of the list subset. The default value of this parameter is the length of the list. This is an optional parameter value.

Note: If a new element already exists in the list, the returned position will be to the rightmost of all element occurrences.

Example

import bisect # import bisect module.
sorted_list = [1, 2, 3, 4, 5, 7] # sorted list.
print (f"given list: {sorted_list}")
new_element = 6
print(f"new element to be added: {new_element}")
print(f"after applying bisect method the index is: {bisect.bisect(sorted_list, new_element)}") # adding new element to the list.
existing_element = 7
print(f"add an existing element: {existing_element}")
print(f"after applying bisect method (add existing element) the index is: {bisect.bisect(sorted_list, existing_element)}") # adding an existing element to the list.

Note:

  • The index in python list starts from 0.
  • The example above uses f-strings in Python for print statements.

Explanation

  • Line 1: We import the bisect module.
  • Line 3: We initialize a sorted list, [1, 2, 3, 4, 5, 7], and assign it to a variable, sorted_list.
  • Lines 7–11: We store 6 in the new_element. Next, we apply the bisect method to the list providing new_element as an argument. 
  • Lines 15–17: We follow the same procedure and apply the bisect method to the list that already has the element to be inserted.

Free Resources