While loop error

Nick Mathewson QnickQm at alum.mit.edu
Fri Feb 1 01:22:45 EST 2002


In article <32c382ad.0201312208.166d5de3 at posting.google.com>, mlorfeld wrote:
> I continue to get the error:
> Traceback (most recent call last):
>   File "Columbus:Desktop Folder:gaus.py", line 19, in ?
>     n=list[i]
> IndexError: list index out of range
> 
> my code is:
> i=0
> j=0
> sum=0
> list=[1,2,3,4,5,6,7,8,9,10,50,100]
> list_length=len(list)
> #G(n)=sum of first n natural numbers
> while i < list_length:
> 	n=list[i]
> 	while j <= n:
> 		sum=sum+j
> 		j=j+1
> 	print sum
> 	j=0
> 	sum=0
> 	i=i+1
> 
> any ideas??

Sadly, no.  The code you list above works just fine for me.  Are you
sure you're running exactly the version you posted? It looks like the
version you're running has advanced i past the bounds of your list.

BTW, you could write the above code a bit more idiomatically like this:

list=[1,2,3,4,5,6,7,8,9,10,50,100] 
for n in list:
    sum = 0
    for j in xrange(n+1):
	sum = sum + j
    print sum

HTH,

-- 
 Nick Mathewson    <Q nick Q m at alum dot mit dot edu>
                      Remove Q's to respond.  No spam.



More information about the Python-list mailing list