Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 63 / 101

Stop looking at everything.

Exploit sorted order to shrink a search interval after every comparison.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Binary search maintains an interval that could contain a target. Comparing with its midpoint lets you discard approximately half of that interval. This gives logarithmic comparisons for sorted random-access data. The precondition matters: searching unsorted values with this algorithm can miss an item that is present.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

binary_search.py
def binary_search(values, target):
    low, high = 0, len(values) - 1
    while low <= high:
        middle = (low + high) // 2
        if values[middle] == target: return middle
        if values[middle] < target: low = middle + 1
        else: high = middle - 1
    return -1
print(binary_search([3, 8, 12, 20, 31], 20))
print(binary_search([3, 8, 12, 20, 31], 7))
↳ EXPECTED OUTPUT
3
-1

03 Under the hood

  1. 1

    low and high describe an inclusive interval. Each update removes the midpoint because it has already been checked.

  2. 2

    When low exceeds high, no candidate remains. Returning -1 is the example’s explicit not-found contract, not a Python indexing recommendation.

  3. 3

    The bisect module finds insertion boundaries. bisect_left returns a possible position, so check the position is in range and equals the target before treating it as a successful search.

04 Your turn, builder

A SMALL MISSION

Use bisect_left to find 12 and report whether it is present.

Reveal one possible solution +
one_possible_solution.py
from bisect import bisect_left
values = [3, 8, 12, 20]
index = bisect_left(values, 12)
print(index < len(values) and values[index] == 12)

05 Check your signal

QUICK SIGNAL CHECK

What is a necessary precondition for this search?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.