-3

I'm facing an issue trying to sum all the elements of a list in python without using the sum() function. So, the thing is, when i run my code i'm able to get the desired result, but below appears this error

IndexError: list index out of range

This is my code:

numbers = [4,8,3,1,-3,3,-5,1,2,-8]
sum = numbers[0]
i = 0
for number in numbers:
    i = i + 1
    sum = sum + numbers[i]
    print(sum)

According to the error message, the problem is in line 6, but i don't understand what's the problem. If anyone could help me, i'll appreciate it.

SHerbes
  • 1
  • 1
  • 1
    `i` goes past the end of your list, and then you try and use it as an index in your list. Why don't you use add `number` to your total and forgo `i` altogether? – khelwood Mar 02 '21 at 00:31
  • You need to do `i = i + 1` *after* you access `numbers[i]` – Barmar Mar 02 '21 at 00:33
  • 1
    Do not use `sum` as a variable. The fact that it is highlighted differently than your other variables should be a tip off that it's bad practice. – Kraigolas Mar 02 '21 at 00:33
  • Think about what happens on the last iteration, `i = i + 1`. What will be the value of `i`? it will be `10`. But `10` is out of bounds for a list with length 10, since lists are 0-indexed. Note, messing with indices is pointless. You **already have `number`** since you are iterating over your list – juanpa.arrivillaga Mar 02 '21 at 00:36
  • Trace your code. Just before line 6, insert a `print` to check `i` and the list length. – Prune Mar 02 '21 at 00:43

1 Answers1

1

You're incrementing i before you use it, so its values go from 1 to len(numbers) instead of 0 to len(numbers)-1.

Instead of indexing into the list, you can use the number variable declared in your loop. That variable takes on the value of each element in the list you're looping over.

for number in numbers:
    total = total + number
    print(total)
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880