Code of the Day
IntermediateRecursion and Search

Search in Python

Implement linear search and iterative binary search, then watch binary search fail on unsorted input to understand why sorted data is a hard requirement.

CS FundamentalsIntermediate10 min read
By the end of this lesson you will be able to:
  • Implement linear search in Python
  • Implement binary search iteratively in Python
  • Verify that binary search produces wrong answers on unsorted input

Two search , side by side. Read through both before running — focus on the loop structure and the invariant each one maintains.

Python — editable, runs in your browser

Reading the binary search loop

The loop maintains an invariant: if target is anywhere in the list, it must be somewhere in lst[lo..hi]. Each iteration:

  1. Computes the midpoint — (lo + hi) // 2 avoids the integer overflow that (lo + hi) / 2 can cause in languages with fixed-width integers.
  2. Compares lst[mid] to target.
  3. Narrows the range by moving lo up or hi down — always preserving the invariant.

When lo > hi, the range is empty: target is not in the list.

Why binary search fails on unsorted data

In the unsorted example above, binary_search compares the middle element and then discards one half — but on unsorted data, the target might be in the discarded half. The algorithm has no way to know. It gives a confident-looking answer that is simply wrong.

This is not a bug to be fixed — it is a precondition violation. Always sort before calling binary search, or use linear search if you cannot guarantee order.

Python's standard library provides bisect.bisect_left(sorted_list, target) for binary search. Use it in production code — it is correct and tested. The hand-rolled version above is for learning the algorithm.

Where to go next

Next: Lab: search — time linear vs binary search on growing inputs, implement a count-using-search function, and try a bonus recursive flatten.

Finished reading? Mark it complete to track your progress.

On this page