The bisect module
Not met yet
bisect does binary search on a sorted list for you. bisect_left(items, x) gives the first place x could go and keep the list in order, which is where the first x is if there is one; bisect_right(items, x) gives the place just after the last x. So bisect_right(items, x) - bisect_left(items, x) counts the copies of x, and insort(items, x) puts x in the right place. They always give a position, never -1 or True.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks bisect_right gives the position of the last matching item, rather than the place just after it.
- Thinks bisect returns -1 for a value that isn't in the list, rather than where it would go.
- Thinks bisect says whether a value is in the list, rather than giving a position.