PythiloLesson 1 of 32 · progress kept in this browser

Halve a sorted list with binary search

A sorted list lets you discard half of the remaining items with one comparison. Keep two bounds, lo and hi, around the part that can still contain the target. Look at the middle, then move one bound past it.

items = [2, 5, 8, 13, 21]
lo, hi = 0, len(items) - 1
mid = (lo + hi) // 2   # 2 -> items[2] is 8
Your task

Write binary_search(items, target) for a sorted list. Return an index where items holds target, or -1 when it is absent.