I haven't been coding for awhile and trying to get back into Python. I'm trying to write a simple program that sums an array by adding each array element value to a sum. This is what I have:
def sumAnArray(ar):
theSum = 0
for i in ar:
theSum = theSum + ar[i]
print(theSum)
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 this:
sum(ar)
But clearly I'm not iterating through the array properly anyway, and I figure it's something I will need to learn properly for other purposes. Thanks!
iis 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)? - Jon Clements♦theSum += ar... - Jon Clements♦