my python code is getting a (list index out of range error) ...can anyone get me a reason why -


given below python code supposed read values list , gets sum of values after squaring each of them.

def squareeach(nums):     in nums[:-1]:         s=nums[i]*nums[i]         nums[i]=s   def sums(num):     sum1=1     in num[:-1]:         sum1=sum1+num[i]     return sum1   def tonumbers(strlist):     in range(len(strlist)):         strlist[i]=int(strlist[i])  file=raw_input("enter filename: ") openf=open(file,'w') openf.write("1 2 3 4 5 6 7 8 9 10") openf=open(file,'r')   s='' in openf:     s=i s=string.split(s)  in range(len(s)):     s[i]=int(i) squareeach(s) s=sums(s) print s 

this program , getting error. why?

python loops iterate on elements (not indices) of list:

for in [1, 2, 4]:    print  # prints 1, 2 , 4 

you'll have modify existing 1 working index of each element:

def squareeach(nums):     in range(len(nums)):         nums[i] = nums[i]*nums[i] 

although make function creates new list instead:

def squareeach(nums):     return [n**2 n in nums] 

Comments

Popular posts from this blog

asp.net mvc 3 - Using mvc3, I need to add a username/password to the sql connection string at runtime -

kineticjs - draw multiple lines and delete individual line -

thumbnails - jQuery image rotate on hover -