user1971598
user1971598

Reputation:

Not understanding why this won't sum up properly

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(grades):
    sum = 0
    for i in grades:
        sum += grades[i]
print(grades_sum(grades))

That's my code and I'm trying to understand why I'm getting an out of index traceback.

Upvotes: 7

Views: 336

Answers (3)

Michael Mauderer
Michael Mauderer

Reputation: 3872

Iterating over a list will return the item in the list, not the index of the item. The correct code as you have written it would look like this:

def grades_sum(grades):
    total = 0
    for grade in grades:
        total += grade 
    return total

Of course as others have answered this can be done much more elegant using sum.

If you actually need the index for something else you could use enumerate like this:

def grades_sum(grades):
    total = 0
    for i, grade in enumerate(grades):
        total += grade #or grades[i] 
    return total

Or if you don't care about retrieving the item at all

def grades_sum(grades):
    total = 0
    for i in range(len(grades)):
        total += grades[i] 
    return total

Upvotes: 14

Blender
Blender

Reputation: 298046

for i in grades: iterates over the elements in grades. It doesn't iterate over the indexes.

To fix your code, just use i instead of grades[i].

Don't be afraid of using print statements. They're excellent for debugging code.

Upvotes: 6

Volatility
Volatility

Reputation: 32300

You don't need to do grade[i] because you're already referencing the elements in the list - all you need to do it replace that with a plain old i

However, there is already a builtin function for this - sum

print(sum(grades))

Upvotes: 13

Related Questions