Below is a compact but fully-featured “classic” binary-search implementation in Python, plus a few useful variants and some quick usage examples.
python
from typing import Sequence, Callable, TypeVar
T = TypeVar('T')
def binary_search(
a: Sequence[T],
x: T,
key: Callable[[T], T] = lambda v: v
) -> int:
"""
Pure-Python binary search.
Parameters
----------
a : sorted sequence (list, tuple, etc.)
x : item you’re looking for
key : optional mapping applied to every element
(default: identity function)
Returns
-------
int : index of x in a | -1 if not found
"""
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
k = key(a[mid])
if k < x:
lo = mid + 1
elif k > x:
hi = mid - 1
else:
return mid
return -1
def bisect_left(a: Sequence[T], x: T) -> int:
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < x:
lo = mid + 1
else:
hi = mid
return lo # insertion point / leftmost ≥ x
def bisect_right(a: Sequence[T], x: T) -> int:
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] <= x:
lo = mid + 1
else:
hi = mid
return lo # insertion point / rightmost ≤ x
Recursive flavor (just for reference)
python
def binary_search_rec(a: Sequence[T], x: T, lo=0, hi=None) -> int:
hi = len(a) - 1 if hi is None else hi
if lo > hi:
return -1
mid = (lo + hi) // 2
if a[mid] < x:
return binary_search_rec(a, x, mid + 1, hi)
if a[mid] > x:
return binary_search_rec(a, x, lo, mid - 1)
return mid
Native alternative: the bisect module
python
import bisect
# index if present, else -1
i = bisect.bisect_left(nums, 7)
print(i if i < len(nums) and nums[i] == 7 else -1)