List index out of range error for index within the range of list

Viewed 35

I am attempting to index a list to pull the first (0) and second (1) items for further calculations. My code currently looks like this:

def calculate_scores(list):
    sat = list[0]
    gpa = list[1]
    weighted_sat = (sat / 160)
    weighted_gpa = (gpa * 2)

This is in the function that I want to use to do the calculations. The part where this function is called in my main looks like this:

testscores = []
semestergrades = []

testscores.append(floatlist[0:4])
semestergrades.append(floatlist[4:])

calculate_scores(testscores)

The list that the testscores list is pulling from is 8 items long, all of them floats - however, when I try to run this code it gives me a 'list index out of range' error for the part where I try to set the variable 'gpa' equal to list[1]. However, it seems to be able to run the first part, setting the variable 'sat' equal to list[0]. Any idea why this is happening?

1 Answers

You're using .append() when you should either be using .extend() or just using the result of the slice:

# floatlist = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]
testscores = []
testscores.append(floatlist[0:4])
# testscores = [[0.5, 1.5, 2.5, 3.5]]

So, how you're currently doing it, testscores is a list with one element, that element being floatlist[0:4]. When you try to use the second element (index 1), you get an IndexError.

You can use .extend() instead of .append() to add all the items in the given iterable to the list. Or, you could just do

testscores = floatlist[0:4]

since list slicing produces a copy of the original anyway.

Related