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

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -