Linear search
Find the first occurrence of an item by checking a list from left to right.
for index, value in enumerate(values): if value == target: return indexreturn -1Visit the array in order until a value matches.
Use a scan when order is unknown
When the items are unsorted, finding one value gives no reliable information about where other values are. Start at index zero and compare each item to the target. Return at the first match to guarantee the earliest matching index.
How it works
Keep track of the next index to inspect. If the current value matches, you can stop, so the earliest match wins. A missing value means every index has to be checked. This makes the scan useful even when the list has no sorted order.
Use a sentinel result
Return -1 if the list ends before finding a match. State that convention in the function’s contract. The scan can finish after one comparison, but an absent target requires n comparisons in the worst case. Only the current index needs to be stored.
Code example
def linear_search(values, target):
for index, value in enumerate(values):
if value == target:
return index
return -1
print(linear_search([7, 2, 9, 2], 2))Check your understanding
Find the first shelf position with the requested label. Use zero-based indexing and -1 for a missing label.
See the example and explanation
- Example 1
- Given
[8, 4, 3, 4], target = 4 - Answer
1 - Example 2
- Given
[8, 4, 3, 4], target = 9 - Answer
-1
Compare in order and return the current position exactly when a match occurs. The second reading of 4 is skipped because index 1 already matched.