Generating and manipulating lists of numbers

The Table command can be used to generate a list of numbers using a predefined mathematical expression. Suppose, for example, that we want to make a list of the squares of the numbers from 1 to 10. This command will generate such a list:

   Table[ n^2, {n, 1, 10} ]
   { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 }

The general format of the Table command is

   Table[ <expression>, <iterator> ]
where <iterator> tells Mathematica what sequence of numbers to use in generating the list from <expression>. In this example, the iterator
   {n, 1, 10}
indicates that the variable n will go from 1 to 10.

The loop variable does not have to be an integer. A list of evenly spaced numbers in the interval between 0 and 1 can be generated by

   Table[ x, {x, 0, 1, 0.01} ]
   { 0, 0.01, 0.02, ..., 0.99, 1 }
Here the iterator
   {x, 0, 1, 0.01}
indicates that the lower limit on the variable x is 0, the upper limit is 1, and the interval between successive values of x is 0.01.

By using more complicated expressions in the Table command, we can generate lists of (x, y) points to be used in ListPlot. Try

   sine = Table[ {x, Sin[x]}, {x, 0, 2 Pi, Pi/100} ]
   ListPlot[sine]
In this example, the expression used to construct the list is itself a list. So the end result is a nested list of (x, y) points suitable for plotting with ListPlot.

So now we know how to build lists. What about taking lists apart? Define a simple list of five numbers:

   list = Table[2^n, {n, 0, 4}]
   { 1, 2, 4, 8, 16 }
To pick out the fourth item in this list, we type
   list[[4]]
   8
The double brackets are Mathematica's way of extracting a single element from a list of items.

Now suppose we have a list of three (x, y) points:

   data = Table[ {n, 3^n}, {n, 0, 2} ]
   { {0, 1}, {1, 3}, {2, 9} }
This is a nested list of three two-element lists, each representing a single (x, y) data point. To get the third point, we type
   data[[3]]
   {2, 9}
Mathematica gives us the third element of the list, which is itself a list of two numbers. To get just the y coordinate of this point, type
   data[[3, 2]]
   9
Here we have two numbers in brackets, which we can think of as indices into the nested list. Basically we are asking Mathematica to take the third element of the original list, and then take the second element of this sub-list.


Other parts of the Mathematica tutorial: