Linear Search

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.

CaseSteps
Best: the first item1
Worst: last item, or missingn
Big-OO(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.

HOME LABS COMMUNITY DASHBOARD