I'm trying to sum the values of a list using a for
loop. This is my code:
def sumAnArray(ar):
theSum = 0
for i in ar:
theSum = theSum + ar[i]
return theSum
I get the following error:
line 13, theSum = theSum + ar[i]
IndexError: list index out of range
I found that what I'm trying to do is apparently as simple as sum(ar)
. But I want to understand: Why do I get this IndexError
, and how should I write the for
loop instead? How does the loop actually work?
For a technical overview of how Python implements for
loops and the iterator protocol, see e.g. How does a Python for loop with iterable work?.
i
is the value of the item you're looping over in the array... so if you had 3 items[10, 11, 12]
you're trying on the first iteration of accessingar[10]
which won't work... You could just use the builtinsum
, eg:sum(ar)
? – ThoriumtheSum += ar
... – Thorium