Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Created January 6, 2026 12:39
Show Gist options
  • Select an option

  • Save pythonhacker/c95f50ac8cb6530f7b803b00adf8d9ac to your computer and use it in GitHub Desktop.

Select an option

Save pythonhacker/c95f50ac8cb6530f7b803b00adf8d9ac to your computer and use it in GitHub Desktop.
Generic sorted list search and locate using bisect
def search(a, x):
""" Locate the index of the leftmost value exactly equal to x """
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
def search_right(a, x):
""" Locate the index of the right most value exactly equal to x """
i = bisect.bisect_right(a, x)
if i and a[i-1] == x:
return i
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment