Lists and algorithms · intermediate
Python Program for Binary Search
Implement binary search in Python on a sorted list, see how it halves the search range each step, and use the bisect module for real code.
- while loop
- floor division //
- sorted lists
- bisect module
Binary search finds a value in a sorted list by checking the middle element and throwing away the half that cannot contain the target. Each step halves the range, so even a list of a million items needs at most 20 steps, compared with up to a million for a simple scan.
The program
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
if items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
numbers = [3, 8, 15, 23, 42, 57, 71, 89]
print(binary_search(numbers, 42))
print(binary_search(numbers, 10))4
-1How it works
- low and high are the first and last positions that could still hold the target.
- mid is the middle position. // keeps it a whole number.
- If the middle value is too small, the target can only be to the right, so low moves past mid; if it is too big, high moves before mid.
- When low passes high the range is empty and the target is not in the list, so the function returns -1.
Watch it run line by line
Visualize the search for 42 and watch low, mid and high close in: mid is 3 (value 23), then 5 (value 57), then 4, which is the answer. Searching for 10 shows low and high crossing.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: With the bisect module
bisect_left returns the position where the target would be inserted to keep the list sorted. If the item at that position equals the target, it is found.
from bisect import bisect_left, insort
numbers = [3, 8, 15, 23, 42, 57, 71, 89]
i = bisect_left(numbers, 42)
print(i, i < len(numbers) and numbers[i] == 42)
insort(numbers, 50)
print(numbers)4 True
[3, 8, 15, 23, 42, 50, 57, 71, 89]Common mistakes
- Running binary search on an unsorted list: it returns wrong answers without any error. Sort first.
- Writing while low < high instead of <=, which misses the target when it is the last remaining element.
- Setting low = mid or high = mid instead of mid ± 1, which can loop forever.
Try it yourself
- Count the steps the search takes and compare with a linear scan for a list of 1,000 numbers.
- Write a recursive version that takes low and high as parameters.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.