Home > OS >  Why linear_search function do not work correctly?
Why linear_search function do not work correctly?

Time:04-09

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)

CodePudding user response:

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

CodePudding user response:

If you want to know if a particular value can be found in a list and you want the index of where it's found then you could do this:

def linear_search(lista, target):
  try:
    return lista.index(target)
  except ValueError:
    pass

This function will return either the index of the target value in the given list or None of it's not found

  • Related