next up previous contents
Next: Membership Up: Common data structures Previous: Sets   Contents

Adding numbers in a list

Here's a handy trick for adding (reps., multiplying) all the elements of a list. To add all the squares of the integers from $1$ to $100$ is easy:

> L:=[];                     
> for i in [1..10] do
for> L:=Append(L,i^2);
for> end for;
> sum:=&+L;
> sum;
385
The
 &+
command iterates the $+$ command over all the elements of L. Likewise, to find their product, now type
> product:=&*L;
> product;
13168189440000

Exercise 10   Compute the sum of all integers of the form $n^3$, $1\leq n\leq 20$.

Exercise 11   Compute the sum of all numbers of the form $(-1)^n/n$, $1\leq n\leq 1000$ and $n$ odd.

The number of elements in a list L is obtained by typing the command #L;. For example,

> L:=[];                     
> for i in [1..10] do
for> L:=Append(L,i^2);
for> end for;
> #L;
returns $10$.



David Joyner 2001-08-22