πβοΈ Python Tricks β Build a Sorted List with Python with the help of the bisect module. bisect is a built-in module used to perform binary search. This module also helps with preserving a list in sorted order. But there are a few things interesting about the bisect module π
The bisect is based on the bisection method for finding the roots of functions. This module comes with six functions divided into two categories. These functions allow you to either find an index of an element or add a new element in the right position.
πFinding Elements with bisect To find the index of an existing element in a sorted list, you want to bisect_left() β οΈImportant: When using bisect to find an element, the method will return the element position or the element's expected position.
π Watch out for unsorted lists Itβs your responsibility to sort the list before passing it to one of the functions. If the elements arenβt sorted, then youβll most likely get incorrect results.
Use this link realpython.com to learn more about the bisect module and binary search with Python.