okai
okai

Reputation: 7

Finding the index of a list

My function gives the error ("IndexError: list index out of range"), and I'm not to sure why, even first putting i = 0. My code is to print the index of the first element that is equal to the target value and if it doesn't equal anything in the list then index = -1. (Using While loop)

Function

def yareyare(list_g, list_size, target):
found = False
i = 0
while i < list_size or not found:
    if target == list_g[i]:
        found = True
        result = i
    else:
        i += 1
if not found:
    result = -1
print("The index is {}".format(result))

Main

# Imports
from index import yareyare

# Inputs
list_g = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list_size = len(list_g)
target = str(input("What is the target value(1-10): "))

#
yareyare(list_g, list_size, target)

Upvotes: 0

Views: 66

Answers (3)

morsecodist
morsecodist

Reputation: 947

There are several problems with this code. I am going to try and fix your errors while changing as little of your original code as possible. There are some things that you are doing that will work that I would advise against, like passing the list length as a parameter rather than using len and using a while loop for this at all.

Your first issue is that target is a string while the goals you compare it to are ints. That means this:

target == list_g[i]

Will never be true. It must be changed to:

int(target) == list_g[i]

Your second problem is that you are looping while i < list_size OR found is false. When you find a match, you set found to false but you never increment i. This means that i will always stay at the same value and therefore it will always equal list_g[i] so you will never increment it. Since i is always less than the list length i < list_size or not found will always be true and you will be trapped in an infinite loop. You should change the or to an and.

Here is your function with the fixes:

def yareyare(list_g, list_size, target):
    found = False
    i = 0
    while i < list_size and not found:
        if int(target) == list_g[i]:
            found = True
            result = i
        else:
            i += 1
        if not found:
            result = -1
        print("The index is {}".format(result))

Upvotes: 0

Alex Zharichenko
Alex Zharichenko

Reputation: 36

There are two simple errors in the code.

First, the boolean logic of the while loop should be and not or because it allows it to loop forever since found doesn't become True until the target is found.

Second, you need to convert target to an int not an str

It should work after that.

Upvotes: 2

Yann Vernier
Yann Vernier

Reputation: 15877

while i < list_size or not found: is the culprit. As long as found is false, the loop continues even if it ran out of list entries. That said, the entire code seems very clumsy; a Python approach would normally use list.index, or for more verbosity, a for loop with enumerate and an else clause.

Upvotes: 1

Related Questions