Search code examples
pythonindexingrangeout

Can anyone help me to understand why i have the error "list index out of range"?


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.


Solution

  • 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)