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

3

39

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

Quarterstaff answered 19/8, 2018 at 16:0 Comment(5)
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 accessing ar[10] which won't work... You could just use the builtin sum, eg: sum(ar) ?Thorium
@JonClements you will notice that I mentioned sum(ar) in my original question as an easier way to do it. I am asking how to properly iterate over array elements.Quarterstaff
(sorry - somehow glanced over that bit) you can just change your loop to be theSum += ar...Thorium
If you want to use the INDEX of each element, rather than the value of each element in a list, you can use enumerateComehither
This is not 3.x-specific.Marvellamarvellous
S
71

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.

Sublet answered 19/8, 2018 at 16:7 Comment(0)
S
7

The for loop iterates over the elements of the array, not its indices.

Consider for example a list ar = [2, 4, 6]: when a loop like for i in ar: runs, the successive values of i will be 2, 4 and 6. The first time through the loop, ar[i] would work (as the last position of the list is 2, a[2] equals 6), but the next iteration would fail (since a[4] is invalid).

Try using for index, value in enumerate(ar):, to get indices along with the values; then theSum = theSum + ar[index] should work just fine.

Sidneysidoma answered 19/8, 2018 at 16:22 Comment(0)
S
2

Iterating over a list or array with code like

ar = [10, 11, 12]
for i in ar:
    print(i)

will actually put the values of the list sequentially in i - so this is the resulting output:

10
11
12

However, in the original code, i is mistakenly treated as an index into the list. In the first iteration for this example, ar[i] would mean ar[10] - which is, of course, an out-of-range index, causing an IndexError.

Sandwich answered 8/9, 2019 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.