Check every item in turn until you find the target, or reach the end.
Python · intermediate · 5 min · 27 steps · free
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
prices = [7, 3, 9, 4, 1]
print(linear_search(prices, 4))
print(linear_search(prices, 8))linear_search(). Its body does not run yet: it runs each time the function is called.prices is created and points to a new list: [7, 3, 9, 4, 1].linear_search(), with items = [7, 3, 9, 4, 1] and target = 4. It gets its own names.i is created with the value 0.i changes from 0 to 1.items[i] == target is false, so the block under it is skipped.i changes from 1 to 2.items[i] == target is false, so the block under it is skipped.i changes from 2 to 3.items[i] == target is true, so the block under it runs.linear_search() has finished, so its names are gone. It prints 3.i is created with the value 0.items[i] == target is false, so the block under it is skipped.i changes from 0 to 1.items[i] == target is false, so the block under it is skipped.i changes from 1 to 2.items[i] == target is false, so the block under it is skipped.i changes from 2 to 3.items[i] == target is false, so the block under it is skipped.i changes from 3 to 4.items[i] == target is false, so the block under it is skipped.for i in range(len(items)).linear_search() has finished, so its names are gone. It prints -1.in or .index() in real Python code; they do the same searchAnswer: 1,000
Answer: No
← Big O: Counting the Work · Binary Search →