# [Tutor] doing maths on lists

Dave Angel davea at ieee.org
Mon Dec 20 13:32:45 CET 2010

```On 01/-10/-28163 02:59 PM, 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))])
>
> So it just should do a sum across all the items in the list:
>
> L0A[0]*cos(L0B[0]+L0C[0]*JME)+ L0A[1]*cos(L0B[1]+L0C[1]*JME)+...
> + L0A[64]*cos(L0B[64]+L0C[64]*JME)= some float number
>
>
> However, I always get this error:
>
> TypeError: can't multiply sequence by non-int of type 'float'
>
> I looked it up and there seems to be some solution using either the "for-in" command or the "map(int,...)" command but I just can't get it to work....
>
>
> Any help will be very much appreciated :)
>
> Greetings from Sydney
> Chris

Look up range(), and notice that the first and 3rd arguments default to
0 and 1 respectively.  So you're just doing range(64), which gives you
the first 64 items in the list.  But you said there were 65, so why
didn't you use 65 ?

Where did you get that python expression?  If you just want a sum,
there's no need for the outer pair of square braces or parentheses.  As
it is, it'll correctly build a list of 1 item, which is the sum of all
but one term of the desired expression.

Anyway, the expression doesn't give an error, if you've really got those
three arrays of floats.  My guess is that you either copied the
expression wrong (use copy/paste), or you've got something else in those
lists.  Make a simple test case, and show the whole thing, including
imports:

from math import cos

JME = 0.4
L0A = [2.3, 4.65]
L0B = [1.8, 2.2]
L0C = [12.1, 4]
limit = len(L0A)

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

print L0

runs fine with Python 2.6 on Linux, producing output of:

-1.52286725666

DaveA
```