Skip to the content

Linear search

Python · Unit 23: Searching and sorting

Searching is answering where something is. The most direct way is to look one by one, from start to end, until you find it.

That is called linear search, and it works with any list, sorted or not.

prices = [40, 15, 70, 15]
for i, p in enumerate(prices):
    if p == 70:
        print("it is at", i)

Prints

it is at 2

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Find the bug

    search should return the position of the 7, which is 1, but it prints -1. Which line has the error?

  4. 4. Complete the code

    Complete it so it reports when the value is not there.

  5. 5. Predict the output

    The 5 is not in the list. What does it print?

  6. 6. Multiple choice

    When nums is a list, what does 9 in nums have to do under the hood?

  7. 7. Find the case that fails

    position(nums, v) should return the position of v, or -1 if v is not in the list. Which call breaks it?

  8. 8. Put the lines in order

    Build the function that gives the position of the first negative number.

  9. 9. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →