This is documentation for Mathematica 8, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)
How to | Work with Nested Lists
Nested lists are lists within a list; they are the principal structure for data in Mathematica and allow for high-dimension arrays and ragged datasets as well as common uses such as matrices.
Create a list of lists to work with:
In[1]:=
Click for copyable input
Out[1]=
Matrices in Mathematica are represented as nested lists. Note that each row corresponds to a sublist in the nested list:
In[2]:=
Click for copyable input
Out[2]//MatrixForm=
Use , the short form of the Part function, to get the second row:
In[3]:=
Click for copyable input
Out[3]=
From row 2, get element 3:
In[2]:=
Click for copyable input
Out[2]=
Get element 3 from each row:
In[3]:=
Click for copyable input
Out[3]=
Use Flatten to remove the nesting:
In[4]:=
Click for copyable input
Out[4]=
Display the flattened data as a column:
In[7]:=
Click for copyable input
Out[7]//MatrixForm=
For comparison, to display the flattened data as a row, add :
In[8]:=
Click for copyable input
Out[8]//MatrixForm=
    
You can operate on the individual sublists of a nested list or on the nested list as a whole.
Set up a dataset:
In[9]:=
Click for copyable input
Out[9]=
In[10]:=
Click for copyable input
Out[10]//MatrixForm=
Most functions map over each sublist within a nested list.
Create four plots from the rows in the dataset:
In[11]:=
Click for copyable input
Out[11]=
Most descriptive statistics functions operate by columns.
Take the mean by column:
In[12]:=
Click for copyable input
Out[12]=
Get the mean of all the numbers by flattening the list:
In[13]:=
Click for copyable input
Out[13]=
    
Create a doubly nested list:
In[14]:=
Click for copyable input
Out[15]//MatrixForm=
Mean now lists the means by each individual nested sublist:
In[16]:=
Click for copyable input
Out[16]//MatrixForm=
Use Flatten to obtain the mean of the entire dataset:
In[17]:=
Click for copyable input
Out[17]=