Real Python
Real Python

@realpython

5 Tweets 1 reads Jan 02, 2023
πŸβš™οΈ 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.

Loading suggestions...