pythonlinear-search

Why linear_search function do not work correctly?


Why this code works only if target==theFirstElement ? it return None even though target==5 or any other element in the list.

def linear_search(lista, target):
    for i in range(8):
        if lista[i]==target:
            return i
        return None

def verify(index):
    if index is not None:
        print("Target found at index:", index)
    else:
        print ("Target not found in list")

numbers =[1,2,3,4,5,6,7,8]

result=linear_search(numbers, 4)

verify(result)

Solution

  • There is a bug with your code: you should return None only once the for loop is done and you visited all the elements:

    def linear_search(lista, target):
        for i, elem in enumerate(lista):
            if elem == target:
                return i
        # if you don't find the target return None
        return None