pythonfor-looptypeerrorindex-error

Why do I get an IndexError (or TypeError, or just wrong results) from "ar[i]" inside "for i in ar"?


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


Solution

  • When looping over a list, the for variable (in this example i) represents the current element of the list.

    For example, given ar = [1, 5, 10], i will have the successive values 1, 5 and 10 each time through the loop. Since the length of the list is 3, the maximum permitted index is 2. Thus, the second time through the loop, when i == 5, an IndexError is raised.

    The code should be like this instead:

    for i in ar:
        theSum = theSum + i
    

    To be able to index into the list, use a range instead of iterating over the list directly:

    for i in range(len(ar)):
        theSum = theSum + ar[i]
    

    This way, i naturally takes on all the valid index values for ar.