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.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}]


This generates an array corresponding to the same nested list.

In[2]:= Array[x^#1 + #2 &, {2, 3}]


Elements not explicitly specified in the sparse array are taken to be 0.

In[3]:= Normal[SparseArray[{{1, 3} -> 3 + x}, {2, 3}]]


Each element in the final list contains one element from each input list.

In[4]:= Outer[f, {a, b}, {c, d}]


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}]


Flattening out sublists.

This generates a array.

In[6]:= Array[a, {2, 3}]


Flatten in effect puts elements in lexicographic order of their indices.

In[7]:= Flatten[%]


Transposing levels in nested lists.

This generates a array.

In[8]:= Array[a, {2, 2, 2}]


This permutes levels so that level 3 appears at level 1.

In[9]:= Transpose[%, {3, 1, 2}]


This restores the original array.

In[10]:= Transpose[%, {2, 3, 1}]


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}]


This applies the function at level 2.

In[13]:= Apply[f, m, {2}]


This applies f to both parts and their indices.

In[14]:= MapIndexed[f, m, {2}]


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}]


This pads with zeros to make a array.

In[17]:= PadRight[%, {2, 3, 3}]