Sub topic 2
Linear Search: Checking Every Element
This chapter assumes you can write loops, conditionals, and functions in Python, and that you know lists use zero-based indexing. Linear search is the simplest answer to the search problem. You look at each element in order until you find the target or run out of elements.
The Working Model
Linear search walks the list from index 0 to the last index. At each position it asks one question: does this element equal the target? If yes, it stops and returns that index. If the loop finishes without a match, it returns a sentinel value meaning "not found." By convention that value is -1, since no real index can be negative in this setting.
Linear search makes no assumptions about the data. The list can be unsorted, contain duplicates, or mix values in any order. Linear search works on all of these, and binary search does not.
The Implementation
def linear_search(items, target):
for i, value in enumerate(items):
if value == target:
return i
return -1
print(linear_search([4, 2, 7, 1], 7)) # 2
print(linear_search([4, 2, 7, 1], 5)) # -1enumerate yields each index and value together, so you never index into the list by hand. The early return i gives you the index of the first match. The return -1 runs only after every element has been checked.
Common Errors
Returning "not found" too early
The most frequent bug puts the failure return inside the loop:
def broken_search(items, target):
for i, value in enumerate(items):
if value == target:
return i
else:
return -1 # exits after checking only items[0]
print(broken_search([4, 2, 7, 1], 7)) # -1, which is wrongYou can only conclude that the target is absent after the loop has seen every element.
Off-by-one ranges
If you write for i in range(len(items) - 1), the last element is never checked. range(len(items)) already stops before len(items), so it covers every valid index.
Returning the last match instead of the first
If you assign result = i on each match and return result after the loop, you get the last matching index. That can be correct, but only if it is what you meant. Decide which occurrence you want and write the code for that.
Useful Variations
The same loop shape handles related tasks. Here are two.
def find_all(items, target):
return [i for i, value in enumerate(items) if value == target]
def find_first(items, predicate):
for i, value in enumerate(items):
if predicate(value):
return i
return -1
print(find_all([3, 1, 3, 2, 3], 3)) # [0, 2, 4]
print(find_first([5, 8, 12, 3], lambda x: x > 10)) # 2find_all cannot stop early, because it has to see every element. find_first generalizes equality to any condition, which is something binary search can only do under strict ordering rules.
How many comparisons all this costs in the best, worst, and average case is covered in the next chapter.
Exercise
Write last_index(items, target) that returns the index of the last occurrence of target, or -1 if it is absent, and stops as soon as it finds the answer.
Show answer
Scan from the end: for i in range(len(items) - 1, -1, -1): if items[i] == target: return i followed by return -1 after the loop. The range starts at the last index and stops before -1, so it checks index 0 too.
Exercise
Why does linear_search([], 3) return -1 without errors?
Show answer
Iterating an empty list runs the loop body zero times, so control falls through to return -1. No index is ever accessed.