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.
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?
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
>>bisect.bisect(mylist, 30) # just returns the position(index) for the new value to be inserted
>>mylist [1, 4, 10, 30, 40, 60]
# To find and also insert at the same time using bisect (insert new value 20 )
[1, 4, 10, 20, 30, 40, 60] # as you see 20 is inserted and also order is maintained properly
That's it. Thanks for taking your time to read my blog. See you in my next article.
Happy coding !!!