Exercise 6: Binary Search in a Sorted List — Possible Solution ==================================================================== numbers = [3, 8, 15, 23, 42, 57, 61, 90] for target in [42, 50, 3, 90]: low, high = 0, len(numbers) - 1 position = -1 while low <= high: mid = (low + high) // 2 if numbers[mid] == target: position = mid break elif numbers[mid] < target: low = mid + 1 else: high = mid - 1 if position == -1: print(f"{target}: not found") else: print(f"{target}: found at index {position}") Example run: 42: found at index 4 50: not found 3: found at index 0 90: found at index 7 WHY THIS WORKS AS AN ANSWER ------------------------------ Look at the middle item. If it is the target, stop. If it is too small, everything at or below mid is ruled out, so low moves to mid + 1; if too big, high moves to mid - 1. The range halves on every pass, so a list of a million items needs about 20 passes. When low passes high the range is empty and the target is not there. position = -1 is the 'not found' marker, and a search must start again from a fresh low and high for every target, which is why they are set inside the for loop. The list must be sorted for any of this to work.