In your last test, the function accesses list[5]
, which is out of range. This causes an IndexError
. The largest index you can access without raising an exception is one less than the length of the list. You can address this by modifying the condition of your while
loop:
while position < len(list):
Or even better, just iterate through the list directly, determining the position using enumerate
:
def linear( target, list ):
""" returns the position of target,
if not found returns -1"""
for idx, element in enumerate(list):
if element == target:
return idx
return -1