Search code examples
pythonlistfunctiontuplesindex-error

Unexpected error: "IndexError: list index out of range" when trying to access a list within a function


def myMax(L):
    print(L)
    f=len(L)
    ind=0
    maxx=L[0]
    for i in range(len(L)):
        if L[i]>maxx:
             maxx=L[i]
             ind=i
    return (ind,maxx)
print(myMax([1, 2, -9, 10]))
print(myMax([]))   

I am quite new to python. Above is code that I have written which takes a list as input and returns a tuple with the index of the highest number and the highest number itself.

For some reason I am getting an "IndexError:list index out of range" on line 5, where "maxx=L[0]"

Any help would be appreciated


Solution

  • You pass empty list : myMax([]) to the function and you point to the first element of this empty list L[0]. You need to check if the list L is not empty.

    Adding the below as the first lines of the function will help you to protect against None or empty list

    if L is None or len(L) == 0:
      raise ValueError('Input list can not be None or empty')