Search through a list of values, looking for either:
- if a target value is in the list
- the location (index) of a target value in the list
General Algorithm
A result of -1 is used to indicate “not found”.
found = -1 for each item in list if item = target value then found = index value end if next item
Find if a value is in a list
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | # target = "fred" found = False for name in names: if name = = target: found = True break # can stop searching if found: print (f "{target} was found" } else : print (f "{target} was not found" } # |
Find location of a value in a list
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | # target = "fred" found = - 1 for name in range ( 20 ): if names[name] = = target: found = name break # can stop searching if found = = - 1 : print (f "{target} was not in list" } else : print (f "{names[found]} had a mark of {mark[found]}" ) # |