Iterating over arrays in Python 3

后端 未结 4 784
忘了有多久
忘了有多久 2020-12-06 09:38

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

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 10:15

    While iterating over a list or array with this method:

    ar = [10, 11, 12]
    for i in ar:
        theSum = theSum + ar[i]
    

    You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:

    10
    11
    12
    

    However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

    Edit You can read this for better understanding of different methods of iterating over array or list in Python

提交回复
热议问题