Before you start this course, you must login to Replit
If you have forgotten your Replit account user name or password, ask your Coder Coach.
If you have forgotten your Replit account user name or password, ask your Coder Coach.
Loops can be user to search lists using the linear search technique.
There are three ways to do this. The first two are the traditional methods, and the third is a method built into Python.
There’s a lot to unpack with the code at first. Take your time and go through lots of examples to help understand it. Use this excellent python visualiser to show the steps involved.
This method inspects every item in the list.
False
before the loop starts (we haven’t found anything at this point) and then True
if the item is found.True
if the current item in the list is the one we are looking for.True
during the search.counter = 0
found = False
while counter < len(item_list):
if item_list[counter] == item_looking_for:
found = True
counter +=1
if found == True:
print(item_looking_for + " has been found in the list")
else:
print(item_looking_for + " is not in the list")
This method uses the found variable as part of the condition.
The loop will only repeat while the counter is <
the length of the list and the found variable is False
. Once the matching item is found, the found varibale is set to True
which ends the loop.
counter = 0
found = False
while counter < len(item_list):
if item_list[counter] == item_looking_for:
found = True
counter +=1
if found == True:
print(item_looking_for + " has been found in the list")
else:
print(item_looking_for + " is not in the list")
This method does the hard work for the coder, but it also abstracts away the detail of how a linear search algorithm really works.
item_list = ["pencil", "ruler", "pen", "eraser", "calculator"]
item_looking_for = "pen"
if item_looking_for in item_list:
print(item_looking_for + " has been found in the list")
else:
print(item_looking_for + " is not in the list")
Make sure to check for the following things in your code: