How to implement binary search in Python

Standalone binary search function that returns the index of a target in a sorted list, or -1 if not found.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

21 lines
Python 3.9+
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    
    return -1

if __name__ == "__main__":
    test_array = [1, 3, 5, 7, 9, 11, 13, 15]
    targets = [7, 13, 2, 15, 1]
    
    for target in targets:
        result = binary_search(test_array, target)
        print(f"Target {target}: index {result}")

Output

stdout
Target 7: index 3
Target 13: index 6
Target 2: index -1
Target 15: index 7
Target 1: index 0

How it works

The function uses two pointers (left and right) to narrow the search interval. By comparing the middle element with the target, it halves the search space each iteration. The loop runs while left <= right, ensuring all elements are considered. Returning -1 when the loop ends indicates the target is not present. This algorithm runs in O(log n) time.

Common mistakes

  • Forgetting that the input list must be sorted for binary search to work
  • Using `left < right` instead of `left <= right`, which can miss edge elements
  • Not updating `mid` correctly with integer division in Python 2 style

Variations

  1. Use the `bisect` module from the standard library (e.g., `bisect_left`) for a built-in binary search.
  2. Recursive implementation that calls itself with a reduced range.

Real-world use cases

  • Finding a user record by ID in a sorted database index before performing a full fetch.
  • Locating a configuration key in a large sorted settings list for fast lookup.
  • Searching for a timestamp in a sorted log array to determine event spans.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.