7
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.

2
  • I think you will find that this method of doing for loops is more useful and less bug prone than the traditional C-style for loop where you use an index variable, etc... (think about whether there could be something even more useful than this method though)
    – Wes
    Jan 12, 2013 at 1:58
  • 2
    You should not name your variable sum, because that's the name of a built-in function, and it can lead to confusion.
    – abarnert
    Jan 12, 2013 at 2:42

3 Answers 3

14

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
1
  • 1
    less confusing if you do not use the variable name sum (as the OP did) just to introduce the Python function sum
    – dawg
    Jan 23, 2013 at 6:52
13

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))
1
  • 1
    Thank you! Assignment told me to avoid using sum().
    – user1971598
    Jan 12, 2013 at 1:23
6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.