← All lessons

Linear search

Sign in · Sign up

Lesson 12.1

The simplest way to find an item is to check them one by one until the right one shows up:

def linear_search(numbers, target):
    for i, x in enumerate(numbers):
        if x == target:
            return i
    return -1

print(linear_search([4, 8, 15, 16, 23, 42], 15))
print(linear_search([4, 8, 15], 99))
  • enumerate gives both the index and the item: i is the position, x the value;
  • the comparison uses a double ==, while if x = target is an error;
  • found — return i right away, the rest of the list can be skipped;
  • not found — return -1, and that return goes after the loop.

The check gives the list numbers and the number target. Write the function linear_search that returns the index of the first match or -1, and print the result.

Hint

Loop over the list together with the numbers, using enumerate.

Found — return i right away. return -1 goes outside the loop: if you put it inside, the function returns -1 on the very first step.