Bisect Module in Python3

This article explains about bisect module in python3

Hello all . Today we will see about python's inbuilt library bisect and how to make use of that library.

When to use Bisect module?

 Suppose you have a sorted list. While adding items to a list , you want to maintain the sorted order and also find the suitable position for new value in list .

# sample sorted list  

mylist = [1, 4, 10, 40, 60]

# add element 30 to a list and also maintain the sorted order of list


# this will add value to end of the list and doesn't maintain the sorted order of a list

Normally how we will solve this problem?

  • Find the index where we have to insert the new value # find_suitable_index(mylist, new_value)
  • Insert the new value with index # mylist.insert(position, new_value)

Worst way to solve the problem

 mylist.append(30) # add the new value to list 

 mylist.sort() # after adding the new value , immediately sort the list

How to Use Bisect Module, effeciently to solve this problem?

 >>import bisect 

 >>bisect.bisect(mylist, 30) # just returns the position(index) for the new value to be inserted


>>mylist.insert(3, 30)

>>mylist                                                                                                                                                                                             [1, 4, 10, 30, 40, 60]

# To find and also insert at the same time using bisect (insert new value 20 )

>>bisect.insort(mylist, 20)


[1, 4, 10, 20, 30, 40, 60] # as you see 20 is inserted and also order is maintained properly


  •   bisect.insort(mylist, new_value) # here   mylist -> should be sorted list initially .If the list is not sorted initially , then results will be inaccurate.
  • Bisect uses binary search algorithm to quickly find and insert values in any sorted sequence

That's it. Thanks for taking your time to read my blog. See you in my next article.

Happy coding !!!




Leave a comment

(Note: Comments are moderated)