|
2.4.3 Nested Lists

Ways to construct nested lists.
This generates a table corresponding to a nested list.
In[1]:= Table[x^i + j, {i, 2}, {j, 3}]
Out[1]= 
This generates an array corresponding to the same nested list.
In[2]:= Array[x^#1 + #2 &, {2, 3}]
Out[2]= 
Elements not explicitly specified in the sparse array are taken to be 0.
In[3]:= Normal[SparseArray[{{1, 3} -> 3 + x}, {2, 3}]]
Out[3]= 
Each element in the final list contains one element from each input list.
In[4]:= Outer[f, {a, b}, {c, d}]
Out[4]= 
Functions like Array, SparseArray and Outer always generate full arrays, in which all sublists at a particular level are the same length.

Functions for full arrays.
Mathematica can handle arbitrary nested lists. There is no need for the lists to form a full array. You can easily generate ragged arrays using Table.
This generates a triangular array.
In[5]:= Table[x^i + j, {i, 3}, {j, i}]
Out[5]= 

Flattening out sublists.
This generates a array.
In[6]:= Array[a, {2, 3}]
Out[6]= 
Flatten in effect puts elements in lexicographic order of their indices.
In[7]:= Flatten[%]
Out[7]= 

Transposing levels in nested lists.
This generates a array.
In[8]:= Array[a, {2, 2, 2}]
Out[8]= 
This permutes levels so that level 3 appears at level 1.
In[9]:= Transpose[%, {3, 1, 2}]
Out[9]= 
This restores the original array.
In[10]:= Transpose[%, {2, 3, 1}]
Out[10]= 

Applying functions in nested lists.
Here is a nested list.
In[11]:= m = {{{a, b}, {c, d}}, {{e, f}, {g, h}, {i}}};
This maps a function f at level 2.
In[12]:= Map[f, m, {2}]
Out[12]= 
This applies the function at level 2.
In[13]:= Apply[f, m, {2}]
Out[13]= 
This applies f to both parts and their indices.
In[14]:= MapIndexed[f, m, {2}]
Out[14]= 

Operations on nested lists.
Here is a nested list.
In[15]:= m = {{{a, b, c}, {d, e}}, {{f, g}, {h}, {i}}};
This rotates different amounts at each level.
In[16]:= RotateLeft[m, {0, 1, -1}]
Out[16]= 
This pads with zeros to make a array.
In[17]:= PadRight[%, {2, 3, 3}]
Out[17]= 
|