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
mylist.append(30)
# 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
>>import bisect
>>bisect.bisect(mylist, 30) # just returns the position(index) for the new value to be inserted
3
>>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)
>>mylist
[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 !!!
Your comment
Your comment has been saved and will be subject to review before it is displayed to other visitors of the website. Thank you for your comment!
Leave a comment
(Note: Comments are moderated)