Searching a List
This is a free course. Log in to run the code exercises and track your progress.
Searching a List
Linear search looks at the elements one by one, from the first, until it finds the value it wants or reaches the end. It works on any list, sorted or not.
roll_numbers = [12, 7, 25, 3, 18]
key = 25
position = -1
for i in range(len(roll_numbers)):
if roll_numbers[i] == key:
position = i
break
if position == -1:
print("Not found")
else:
print("Found at position", position + 1) # Found at position 3
The program prints position + 1 because people count positions from 1 while Python counts indexes from 0. The break stops the search as soon as the value is found, so the program does not keep looking for nothing.
Python's own key in roll_numbers and roll_numbers.index(key) do the same search for you, but writing it yourself shows exactly how it works.
The first line holds a list of integers and the second line a value to search for. Print Found at position P (counting from 1) for its first occurrence, or Not found.
nums = list(map(int, input().split()))
key = int(input())
position = -1
# search nums for key
if position == -1:
print("Not found")
else:
print("Found at position", position + 1)Log in to edit and run this code.