[Tutor] Why is my list index going out of range

Alan Gauld alan.gauld at btinternet.com
Tue Apr 23 10:42:07 CEST 2013


On 23/04/13 02:47, Jim Mooney wrote:
> Okay, what am I doing wrong here?

> primeList = [1]
> numList = list(range(2,101))
> for e in numList:
>    for f in primeList:
>      if numList[e] % primeList[f] != 0: #list index out of range

for lops in Python do not generate indexes they return the actual 
entries in the list. They are like a foreach loop in other languages.

What you are doing is like

pets = ['cat', 'dog','mouse']
for animal in pets:
     if pets[animal] == 'rabbit':
        print 'thats weird'

You cannot use the animal string as an index.
You use it directly like so:

pets = ['cat', 'dog','mouse']
for animal in pets:
     if animal == 'rabbit':
        print 'thats better'

Once you get used to this style of loop it is much easier
than trying do do things with indexes.

In your case its doubly confusing because the contents of your lists are 
numbers that could be used as indexes but would not give the result you 
expect. You were lucky that you started with a list of one element which 
was not zero.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list