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

Dave Angel davea at davea.name
Tue Apr 23 04:03:18 CEST 2013


On 04/22/2013 09:47 PM, Jim Mooney wrote:
> Okay, what am I doing wrong here? I'm generating primes from a list
> and getting "list index out of range," but since the for loops
> controls the indexes I don't see how that's happening. I thought it
> was the list append, but I commented that out and put in a print
> statement, and I still got the line 5 error:
>
> primeList = [1]
> numList = list(range(2,101))
> for e in numList:
>    for f in primeList:

e and f are now values from the lists;  they are *not* indexes into the 
list.
>      if numList[e] % primeList[f] != 0: #list index out of range

        if e % f != 0:    #will get rid of the exception

>        primeList.append(numList[e])
>

Unfortunately, you still have an algorithm bug.  But now that you 
shouldn't get exceptions, I'll leave you to find the bug.



-- 
DaveA


More information about the Tutor mailing list