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.
Python code
21 linesdef 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
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
- Use the `bisect` module from the standard library (e.g., `bisect_left`) for a built-in binary search.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.