Home > Blockchain >  Python: Getting IndexError: list index out of range, but can't figure out why
Python: Getting IndexError: list index out of range, but can't figure out why

Time:03-11

I am trying to make a function where i find the highest y value of a list input with the format: list([x , y], [x, y]...

line 2, I found somewhere and copied, and i think i kind of understand it, as it finds the nested list with the highest y value, and assigns that y value to max_value variable. The issue comes when I try to find out what index that nested list is placed in the list. I try to find that by using a for loop, but i get this error, and can't understand why:

(line 4, in find_highest if coordinates([i] [1]) == max_value: IndexError: list index out of range).

From what I understand the I should have a value from 0-4 in this case, and that is within the indexes of the list I put in. Here is my code so far:

def find_highest(coordinates):
    x_value, max_value = max(coordinates, key=lambda item: item[1])
    for i in range(len(coordinates) - 1):
        if coordinates([i] [1]) == max_value:
            index = i
    return index


print(find_highest([[96, 33], [200, 96], [30, 690], [59, 9], [220, 93]]))

CodePudding user response:

Don't know why you have added the parentheses. Just change the line from

    if coordinates([i] [1]) == max_value:

to:

    if coordinates[i][1] == max_value:

and it should work.

CodePudding user response:

You need to remove the curly brackets:

if coordinates[i][1] == max_value:

otherwise, the interpreter will consider the 'coordinates' a function

  • Related