Binary search in Python
The binary search loop: while low <= high, check the middle item of a sorted list, then move low or high to halve the search range each time.
Understanding Binary search in Python in VCE Software Development U3O1
What it does: Setting low to mid + 1 throws away the lower half, which halves the search range. The loop keeps going while low is less than or equal to high, because that means there are still items left to check. A list index must be a whole number. // gives a whole number, but / gives a float like 2.5 and causes an error. If the middle item is too small, the target must be in the upper half. Moving low up past mid discards the lower half. Python list indexes start at 0 and the last index is len(numbers) - 1. Using len(numbers) would go past the end of the list.
Common mistakes: The loop must keep running while low is less than or equal to high. With >= the loop will not run properly. It should be while low <= high:. Binary search must start at the first index, which is 0. Starting low at 1 skips the first item in the list. It should be low = 0.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 142–155) and word search (Modules 142–166).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
while low <= high:Fill in the Blanks
Spot the Error
Student with a class code? Join your class →