Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How it works...

The bisect module uses dichotomic searching to look for the point of insertion of an element in a sorted container.

If an element exists in the array, its insertion position is exactly where the element is (as it should go exactly where it is):

>>> values = [ 1, 3, 5, 7 ]
>>> bisect.bisect_left(values, 5)
2

If the element is missing, it will return the position of the next, immediately bigger element:

>>> bisect.bisect_left(values, 4)
2

This means we will get a position even for elements that do not exist in our container. That's why we compare the element at the returned position with the element that we were looking for. If the two are different, it means that the nearest element was returned and so the element itself was ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content