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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)