Constructing Lists

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

Range[n]the list
Table[expr,{i,n}]the values of expr with i from to n
Array[f,n]the list
NestList[f,x,n] with up to n nestings
Normal[SparseArray[{i1->v1,...},n]]a length n list with element being
Apply[List,f[e1,e2,...]]the list

Some explicit ways to construct lists.

This gives a table of the first five powers of 2.
In[1]:=
Click for copyable input
Out[1]=
Here is another way to get the same result.
In[2]:=
Click for copyable input
Out[2]=
This gives a similar list.
In[3]:=
Click for copyable input
Out[3]=
SparseArray lets you specify values at particular positions.
In[4]:=
Click for copyable input
Out[4]=
You can also use patterns to specify values.
In[5]:=
Click for copyable input
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.

Table[expr,{i,list}]the values of expr with i taking on values from list
Map[f,list]apply f to each element of list
MapIndexed[f,list]give for the i^(th )element
Cases[list,form]give elements of list that match form
Select[list,test]select elements for which is True
Pick[list,sel,form]pick out elements of list for which the corresponding elements of sel match form
TakeWhile[list,test]give elements from the beginning of list as long as is True
list[[{i1,i2,...}]] or Part[list,{i1,i2,...}]
give a list of the specified parts of list

Constructing lists from other lists.

This selects elements less than 5.
In[6]:=
Click for copyable input
Out[6]=
This takes elements up to the first element that is not less than 5.
In[7]:=
Click for copyable input
Out[7]=
This explicitly gives numbered parts.
In[8]:=
Click for copyable input
Out[8]=
This picks out elements indicated by a in the second list.
In[9]:=
Click for copyable input
Out[9]=

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

Sow[val]sow the value val for the nearest enclosing Reap
Reap[expr]evaluate expr, returning also a list of values sown by Sow

Using Sow and Reap.

This program iteratively squares a number.
In[10]:=
Click for copyable input
Out[10]=
This does the same computation, but accumulating a list of intermediate results above 1000.
In[11]:=
Click for copyable input
Out[11]=

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

New to Mathematica? Find your learning path »
Have a question? Ask support »