# Difference between for i in my_list and for i in range(len(my_list))

#1

Hello everyone,
I’m currently going through exam statistics exercises in python, and I’ have a following issue:
While trying to loop over a list, using expression:

``````  for i in scores:
total+= scores[i]
``````

returns a index out of range error, while

``````  for i in range(len(scores)):
total+= scores[i]
``````

works just fine.
Could somebody explain to me why is that? I thought that both expressions should work the same.

Thanks

#2

One iterates directly over items in the list, the other iterates over a range of indices the length of the list.

That one would be written as just the item…

``````total += i
``````

Eg.

``````n = ['apple', 'banana', 'cherry', 'date', 'eggplant', 'fiddlehead', 'grape']

m = len(n)   =>  7

range(m)     =>  [0, 1, 2, 3, 4, 5, 6]

for i in range(m):
print i

0
1
2
3
4
5
6

for j in n:
print j

apple
banana
cherry
date
eggplant
grape

for i in range(m):
print n[i]

apple
banana
cherry
date
eggplant
grape``````

#3

Thanks for your reply mtf, although I still don’t understand why one gives desired result and the other returns error. Could you please elaborate?
Thanks a lot.

#4

Will need a link to the exercise to explore this further.

#6

Guessing does not cut it. It looks more like the grades_sum() exercise.

#7

#8

Which method is giving the error? All three below return the same result:

``````def grades_sum(scores):
return sum(scores)
``````
``````def grades_sum(grades):
total = 0
``````
``````def grades_sum(grades):
total = 0
``````

#9

As I said in the original post,

``````for i in scores:
total+= scores[i]
``````

resulted in error, while the below:

``````  for i in range(len(scores)):
total+= scores[i]
``````

was working fine, which caused my confusion, since I’ve expected both to give the same result.
Thanks

#10

But what is the error message?

The above will raise an exception since any values greater than the length of the list will result in an index out of range error.

``````i in scores
``````

`i` is an item in the list, not an index.

``total += i``

#11

The error was an index out of range error

The above will raise an exception since any values greater than the length of the list will result in an index out of range error.

Okay, I understand now. I thought i was the index, and not the particular item in the list.
Thanks a lot for the explanation!

#12

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.