Searching#

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:

Try it live and search for different targets:

>>> def linear_search(data: list, target) -> int:
...     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.