B2.4.2 · Searching

Linear search

Python · step by step

Linear search

Check values in order; stop at the first match.

Select Play or Next line to follow Python execution.

Python implementation

The highlight marks the next line to execute. Values show the state before that line.

def linear_search(items, target):    for index in range(len(items)):        if items[index] == target:            return index    return -1

The first item is the best case, O(1). The last item or an absent target takes O(n) time. This implementation uses O(1) auxiliary space.

Keep exploring

Return to the linear search lesson →

All B2.4 animations →

All practice & resources →