Skip to main content

Binary search on python sorted sequences

Project description

Binary Search in Python

Binary search on already sorted sequences (list, tuple) to get the first element >= or > a value (similar to C++'s std::lower_bound and std::upper_bound).

Requires python >=3.5 for the typing module and >= 3.4 for the enum module, but you can easily extract the search function from binary_search/ if you need it for a lower version.


  1. pip install binary-search


See for more sample usage.

import binary_search as bs

sorted_sequence = (2, 5, 7, 9)
a =, 5)
print(a) # 1 - the index of the first element >= 5

b =, 6)
print(b) # 2 - the index of the first element >= 6 (element 2 with value 7)

You can also use a custom key in the same way as sorted

import binary_search as bs
import random

# sequence of 10 random pairs of integers
sequence = [(random.randint(), random.randint()) for _ in range(10)]
# sort and search just using the first integer
key = lambda pair: pair[0]

sorted_sequence = sorted(sequence, key=key), [5, None], key=key)

Development and testing

  1. Fork the repository
  2. Clone your fork
  3. Install it in editable mode pip install -e .
  4. Make any changes and add new tests to
  5. Run pytest python -m pytest
  6. Commit and push to your fork
  7. Make pull request (merge your fork back to main repo)

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for binary-search, version 0.3.0
Filename, size File type Python version Upload date Hashes
Filename, size binary_search-0.3.0.tar.gz (2.7 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page