Using Bisect Module in Python

Hello everyone, In this tutorial, we’ll be learning about Bisect Module in Python which is based on the Bisection Algorithms and can be used to maintain a list in a sorted manner. We can insert any element or find its preferred index in a list such that the list remains sorted without applying any other operation. Bisect is an in-built Module, therefore we do not require to install it. Also, Note that Bisect is a highly optimized Module that can be used to increase the performance of our program.

You can also check this out: Bisect module – Array Bisecting Algorithms in Python

Working with Bisect to find Index in Python

By index, we mean that we are finding the index in a list at which if the desired element is inserted, Our list will remain sorted.

import bisect

a = [1,2,3,4,5,7,8,9,10]


Let us see the output of the above program and try to understand it.

Element 6 can be inserted at index- 5
Element 9 can be inserted at index- 8
Element 9 can be inserted at index- 7
Element 9 can be inserted at index- 8
  • If we insert 6 at index position 5, starting from index 0 (list indexing start from 0), We see that the list will remain sorted assuming the list is already sorted before insertion. This Index is returned by the bisect(list, element) function of the bisect Module.
  • If we try to insert an element that is already present then we can either get the index of the leftmost or rightmost suitable index position using bisect_left() or bisecct_right() functions respectively.
  • Note that the bisect() function is the same as bisect_right() as it will also give the rightmost suitable index position.

Note: These functions only give the index position value and do not insert the element, Therefore, to make changes in the list we can use the insort() function. Let us see how it works.

Working with Bisect to Insert Element

See the code and the output below and try to understand how insort(list, element) function works. We will find it easy to understand as it is similar to the bisect() function we’ve just seen.

print("list after inserting 6 at index 5 is: ",a)

The output after running above code will be:

list after inserting 6 at index 5 is:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

It works as per our expectations and now our list has been changed. We want you to try the insort_left() and insort_right() functions to see how they behave on a list.

We hope you like this tutorial and if you have any doubts, feel free to leave a comment below.

You may like to learn.

How to add Emojis in a Python Program

Extensions in Flask explained and how to add them

How to convert .py to .exe

Leave a Reply

Your email address will not be published. Required fields are marked *