Skip to content Skip to sidebar Skip to footer

Python Error - List Index Out Of Range?

Anyone help me see why I keep getting 'list index out of range' as an error ?? def printInfo(average): average.sort() # sorts the list of tuples average.reverse() # rev

Solution 1:

You hard coded the range of your loop and it is probably greater than the length of the list

A quick fix is

defprintInfo(average):
    average.sort()  # sorts the list of tuples 
    average.reverse()  # reverses the list of tuples print('\tDate\t\tAverage Price')
    for i inrange(len(average)): #Change was hereprint("\t{:.2f}".format(average[i][2], average[i][1], average[i][0]))

however, a better fix is to use iteration:

defprintInfo(average):
    average.sort()  # sorts the list of tuples 
    average.reverse()  # reverses the list of tuples print('\tDate\t\tAverage Price')
    for a in average: # loops through each item of averageprint("\t{:.2f}".format(a[2], a[1], a[0]))

Post a Comment for "Python Error - List Index Out Of Range?"