This is documentation for Mathematica 5, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)

Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Manipulating Lists /

2.4.1 Constructing Lists

Lists are widely used in Mathematica, and there are many ways to construct them.

Some explicit ways to construct lists.

This gives a table of the first five powers of two.

In[1]:= Table[2^i, {i, 5}]

Out[1]=

Here is another way to get the same result.

In[2]:= Array[2^# &, 5]

Out[2]=

This gives a similar list.

In[3]:= NestList[2 #&, 1, 5]

Out[3]=

SparseArray lets you specify values at particular positions.

In[4]:= Normal[SparseArray[{3->x, 4->y}, 5]]

Out[4]=

You can also use patterns to specify values.

In[5]:= Normal[SparseArray[{i_ -> 2^i}, 5]]

Out[5]=

Often you will know in advance how long a list is supposed to be, and how each of its elements should be generated. And often you may get one list from another.

Constructing lists from other lists.

This selects elements larger than 5.

In[6]:= Select[{1, 3, 6, 8, 10}, # > 5&]

Out[6]=

This explicitly picks out numbered parts.

In[7]:= {a, b, c, d}[[{2, 1, 4}]]

Out[7]=

Sometimes you may want to accumulate a list of results during the execution of a program. You can do this using Sow and Reap.

Using Sow and Reap.

This program iteratively squares a number.

In[8]:= Nest[#^2&, 2, 5]

Out[8]=

This does the same computation, but accumulating a list of intermediate results above 1000.

In[9]:= Reap[Nest[(If[# > 1000, Sow[#]]; #^2) &, 2, 6]]

Out[9]=

An alternative but less efficient approach involves introducing a temporary variable, then starting with t = , and successively using AppendTo[t, elem].