Linear Search
Searching: lesson 1 of 5
The simple one that always works. Often that's enough.
Lesson 1 of 5 · 3 min
Linear Search
Step 1 of 7
targetgraychecks0
i
red
blue
green
teal
gray
pink
012345
Linear search needs no order and no setup — it just looks at everything until it finds gray.
The Idea
Check items one at a time until you find the target or run out of items. It needs no ordering and no preparation at all. The worst case is O(n), and for small or unsorted data that is genuinely the right choice.
Real-World Example
Waiting at the baggage carousel, you inspect each bag as it rolls past. The bags arrive in no useful order, so there is nothing smarter to do than look at every one until yours appears.
The Code
def linear_search(items, target):
for i, item in enumerate(items):
# check one at a time, in order
if item == target:
return i # found it: return the index
return -1 # not here
print(linear_search(["red", "blue", "green"], "green")) # 2
print(linear_search(["red", "blue", "green"], "pink")) # -1
Your turn
Put the steps in the right order.
- Return -1 because nothing matched
- Compare the current item to the target
- Start at index 0
- Move to the next index when there is no match
Mini quiz
1 / 3