Check every item
Linear search is the simplest search: start at the beginning and check each item until you find what you want, or run out of items.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i # found it: return the position
return -1 # not there
books = ["Dune", "Emma", "Ulysses", "Hamlet"]
print(linear_search(books, "Ulysses"))
print(linear_search(books, "Matilda"))Output
2 -1
Think of it like this: Looking for your keys by checking every pocket, one after another.
| Case | Steps |
|---|---|
| Best: the first item | 1 |
| Worst: last item, or missing | n |
| Big-O | O(n) |
Python's in, list.index() and list.count() all do a linear search.
Tip: Linear search is the right choice when the list is small, unsorted, or you only search once.