Course 3.1Lesson 1 of 5
Linear search looks at the items one by one from the start until it finds the target. It works on any list, in order or not. A search function usually gives back the position, and minus one when the target is not there. In the worst case, when the target is last or missing, it checks every item, so n items need n checks. The method index and the word in search a list for you. The same loop can find all the positions of a target, or the first item that passes a test.
Try the code and the simulations beside the lesson.
After this lesson you can
index and in when they are enough.You lose a card in a pile. The simplest way to find it: look at the cards one by one. This is linear search. You do not need the pile to be in any order.
Predict first. Where is the number 7? How many items does the loop look at? Then run it.
The loop looks at the positions 0, 1 and 2. The item at position 2 is 7, so it says so, and break leaves the loop. It did not need to look at the last two items. The break is what makes the search stop early.
A search is a good job for a function: the list and the target go in, and the answer comes out.
Python does a linear search for you: marks.index(90) gives the position (and a ValueError if it is missing), and 90 in marks gives True or False. Use them when you only need the answer. Write your own loop when you need to count the checks, or when the test is more than "equals".
A search can ask different questions. Here are two.
On average, a target that is there needs about half the list. A missing target always needs every check.
return -1 is inside the loop, the function gives up after the first item.-1 as a position without checking. items[-1] is the last item.index for a missing target. A ValueError. Ask with in first, or use your own function.break or return. The loop goes on although the target was found.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
-1 when the target is not there.n checks for n items.index() and in search a list for you.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
find_all([4, 7, 2, 7], 7) give?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.