This Linear Search lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
Linear search checks each item until it finds the target or runs out of items. It works on an unsorted list.
index does this for you and raises ValueError when the value is missing.
Example 1: Start here
On a long unsorted list, linear search is the honest cost. Sorting first only helps if you search many times.
skills = ["Python", "SQL", "Git"] # a list; the values stay in this order
print(skills.index("SQL")) # where the first match sits
Example 2: Walk the values
Linear Search starts by visiting one value at a time. Read the printed lines from top to bottom.
values = [20, 3, 11, 7] # a list; the values stay in this order
for value in values: # repeat the indented lines once per value
print(value)
Example 3: Keep the largest
Many data-structure lessons reduce a list to one answer. This one remembers the largest number seen so far.
values = [20, 3, 11, 7] # a list; the values stay in this order
best = values[0] # the first value
for value in values: # repeat the indented lines once per value
if value > best: # run the indented lines only when this is true
best = value # another name for the same value
print(best)
Example 4: Search for a target
A search asks one yes-or-no question: is the target in the collection? Linear Search builds on that question.
values = [3, 20, 11] # a list; the values stay in this order
target = 20 # a whole number
print(target in values) # in is True when the value is found
