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 to do it...

For this recipe, the following steps are to be performed:

  1. Take the following set of elements:
>>> values = [ 5, 3, 1, 7 ]
  1. Looking up an element in the sequence can be done through the in operator:
>>> 5 in values
True
  1. Sorting can be done through the sorted function:
>>> sorted_value = sorted(values)
>>> sorted_values
[ 1, 3, 5, 7 ]
  1. Once we have a sorted container, we can actually use the bisect module to find contained entries faster:
def bisect_search(container, value):
    index = bisect.bisect_left(container, value)
    return index < len(container) and container[index] == value
  1. bisect_search can be used to know whether an entry is in the list, much like the in operator did:
>>> bisect_search(sorted_values, 5)
True
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