1
def linsearch(list, target):
    for i in range(0, len(list)):
            if (list[i] == target):
                return (i)
            else:
                return ("not in list")

list1 = [1,2,3,4,5]

print(linsearch(list1,1))

This is the python program. Whenever I put target as 1 it returns correct index that is 0, but for all other cases it gives the else case prompt i.e. "not in list"

  • What have you tried to resolve the problem? Where are you stuck? I would assume that your `for` loop should not return `not in list` after having checked the very first item – Nico Haase Jul 06 '23 at 13:43
  • 1
    You should put the else condition not as an else but as a separate statement outside of the for. – Marijn Jul 06 '23 at 13:43
  • Please don't remove the code from your question. Share it in text form, not hidden in a screenshot – Nico Haase Jul 06 '23 at 13:44
  • 1
    Also please don't add images of code, what you had before was better (it just needed code formatting, select the code and press the `{}` button). – Marijn Jul 06 '23 at 13:44
  • 1
    If you place your code inbetween `\`\`\`python` and `\`\`\``, the code will be properly highlighted. – Felix Jul 06 '23 at 13:50

1 Answers1

1

You sohuld not return inside the else statement. If you have a return in both the if and the else, you will never proceed to the second iteration of your for loop.

You can instead just ommit the else completely and just do nothing when list[i] does not match your target. And only when your code reaches the ent of the for loop without returning on a match, return the "not in list" value.

def linsearch(list, target):
    for i in range(0, len(list)):
        if (list[i] == target):
            return (i)
    return ("not in list")
Felix
  • 1,066
  • 1
  • 5
  • 22