Searching#

Note

Source: Adapted from the C# edition (arrays/searching.rst). Python’s in operator and list.index() replace the explicit C# IntArrayLinearSearch() function. The bisect module provides binary search for sorted lists.

Searching finds whether a value exists in a collection and, if so, where. Python provides both built-in conveniences and the ability to write searches explicitly.

Writing Linear Search Explicitly#

Writing the search as a loop is useful when you need more control — for example, to return the index on the first match, or to search through a list of objects by a field:

def linear_search(data, target):
    for i, value in enumerate(data):
        if value == target:
            return i
    return -1    # not found
data = [12, 8, -5, 22, 9, 2]
print(linear_search(data, 9))    # 4
print(linear_search(data, 99))   # -1

Performance Comparison#

Search type

Time

Requirement

in / linear

O(N)

Any list

bisect

O(log N)

List must be sorted

For small lists the difference is negligible. For large sorted lists, binary search is dramatically faster.