Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Binary Search

Medium · 55 XP

Implement binary search returning the index of a target in a sorted list, or -1. Print the index for four targets and the number of comparisons for one of them.

Target output
0
4
9
-1
Blank · autosaved
PYbinary-search.py
Run your code to check it…
Guide

How to approach Binary Search

Binary search works on sorted data by halving the search space at every step. Keep two bounds, lo and hi, look at the middle element, and throw away the half that cannot contain the target.

If the middle value is too small, the target must be to its right, so move lo to mid + 1. If it is too big, move hi to mid - 1. Loop while lo <= hi; when the bounds cross, the target is not there and you return -1.

Worked through on this data

  1. Searching for 9 in the ten values: lo = 0, hi = 9, mid = 4, and values[4] is 9. Found on the first comparison: index 4.
  2. Searching for 8: mid = 4 (9 is too big, so hi = 3), then mid = 1 (3 is too small, so lo = 2), then mid = 2 (5, lo = 3), then mid = 3 (7, lo = 4).
  3. Now lo = 4 is greater than hi = 3, so 8 is not in the list: -1. 1 and 19 are found at indices 0 and 9.

Common mistakes

  • Looping while lo < hi skips the last remaining candidate, so a target in the final position can be missed.
  • Setting lo = mid instead of mid + 1 can loop forever when lo and hi are next to each other.
  • Running it on unsorted data returns wrong answers silently, with no error.

Time and space

Each step halves the range, so it is O(log n) time and O(1) space. A million sorted items need at most 20 comparisons; a linear scan might need a million.

Where this shows up

Database indexes, git bisect hunting the commit that broke a build, and Python's own bisect module all rest on this halving idea.

Take it further

Count the comparisons each search makes and print them, then compare your results with bisect.bisect_left from the standard library.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path