[Tutor] doing maths on lists

Steven D'Aprano steve at pearwood.info
Mon Dec 20 13:06:21 CET 2010


Chris Begert wrote:
> Bonjour
> 
> I have three lists with 65 float items and would like to do the following sum:
> 
> L0 = ([sum(L0A[i]*cos(L0B[i]+L0C[i]*JME) for i in range(0,64,1))])
[...]
> However, I always get this error:
> 		
> TypeError: can't multiply sequence by non-int of type 'float'		

Works for me:


 >>> from math import cos
 >>> L0A = [i for i in range(64)]  # make up some data
 >>> L0B = [2*i+3 for i in range(64)]
 >>> L0C = [3*i-2 for i in range(64)]
 >>> JME = 2
 >>> L0 = ([sum(L0A[i]*cos(L0B[i]+L0C[i]*JME) for i in range(0,64,1))])
 >>> L0
[39.022477151098606]


Please compare what you typed in your email with the code you are trying 
to run. I think you will find that you have something like this by mistake:

([sum(L0A*cos(L0B[i]+L0C[i]*JME) for i in range(0,64,1))])

Notice that it has L0A*cos(...) instead of L0A[i]*cos(...).


Some other comments:

Why is the sum stored in a one-item list? I don't think you need either 
of the two outer-most brackets, ([...]). That is:

L0 = sum(L0A[i]*cos(L0B[i]+L0C[i]*JME) for i in range(0,64,1))


You can simplify the call to range: range(0, 64, 1) is just a long way 
of writing range(64):

L0 = sum(L0A[i]*cos(L0B[i]+L0C[i]*JME) for i in range(64))


Rather than explicitly specify the indexes used, a better solution is to 
use zip() like this:

L0 = sum(a*cos(b+c*JME) for a,b,c in zip(L0A, L0B, L0C))



-- 
Steven



More information about the Tutor mailing list