[Tutor] Why is my list index going out of range
Mitya Sirenef
msirenef at lightbird.net
Tue Apr 23 04:02:42 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:
> if numList[e] % primeList[f] != 0: #list index out of range
> primeList.append(numList[e])
>
> print(primeList)
You are doing, basically:
x = [1]
for f in x:
x[f]
x[1] is out of range, because x is length=1, and
the last valid index is 0.
-m
>
> --
> Jim Mooney
>
> The Real Reason Things Keep Going Wrong:
>
> At the beginning of time, God set a Magic Top Spinning... and spinning...
> and spinning... and spinning... and spinning... and spinning... and
> spinning...
>
> After a few hundred million years God got bored and gave the top a good
> kick; so it went rebounding away, flinging off planets and stars and
> dinosaurs, and later, people who wrote about dinosaurs.
>
> Then God realized that although Order and Regularity are virtuous, if you
> want interesting stories, now and then you have to give things a good Kick!
>
> This explains a lot.
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
--
Lark's Tongue Guide to Python: http://lightbird.net/larks/
More information about the Tutor
mailing list