Linear Search

Check every item in turn until you find the target, or reach the end.

Python · intermediate · 5 min · 27 steps · free

What you'll learn

linear_search.py

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))

Step by step

  1. Python defines the function linear_search(). Its body does not run yet: it runs each time the function is called.
  2. prices is created and points to a new list: [7, 3, 9, 4, 1].
  3. Python calls linear_search(), with items = [7, 3, 9, 4, 1] and target = 4. It gets its own names.
  4. i is created with the value 0.
  5. items[0] is 7, not 4. Keep looking.
  6. i changes from 0 to 1.
  7. items[i] == target is false, so the block under it is skipped.
  8. i changes from 1 to 2.
  9. items[i] == target is false, so the block under it is skipped.
  10. i changes from 2 to 3.
  11. items[i] == target is true, so the block under it runs.
  12. Found 4 at index 3. The function returns at once: no need to check the rest.
  13. linear_search() has finished, so its names are gone. It prints 3.
  14. Now search for 8, which is not in the list.
  15. i is created with the value 0.
  16. items[i] == target is false, so the block under it is skipped.
  17. i changes from 0 to 1.
  18. items[i] == target is false, so the block under it is skipped.
  19. i changes from 1 to 2.
  20. items[i] == target is false, so the block under it is skipped.
  21. i changes from 2 to 3.
  22. items[i] == target is false, so the block under it is skipped.
  23. i changes from 3 to 4.
  24. items[i] == target is false, so the block under it is skipped.
  25. Python moves to the next item of the loop: for i in range(len(items)).
  26. Every item was checked without a match: return -1, meaning "not found".
  27. linear_search() has finished, so its names are gone. It prints -1.

Common mistakes

Best practices

Key takeaways

Check yourself

Linear search on 1,000 items, target missing: checks?

Answer: 1,000

Does linear search need a sorted list?

Answer: No

·

More in Complexity and Searching