Nested Lists

Ways to construct nested lists.

This generates a table corresponding to a 2×3 nested list:

Table[x^i+j,{i,2},{j,3}]

This generates an array corresponding to the same nested list:

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

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

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

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

Outer[f,{a,b},{c,d}]

Functions like (RefLink[Array, paclet:ref/Array]), (RefLink[SparseArray, paclet:ref/SparseArray]), and (RefLink[Outer, paclet:ref/Outer]) always generate full arrays, in which all sublists at a particular level are the same length.

Functions for full arrays.

The Wolfram Language can handle arbitrary nested lists. There is no need for the lists to form a full array. You can easily generate ragged arrays using (RefLink[Table, paclet:ref/Table]).

This generates a triangular array:

Table[x^i+j,{i,3},{j,i}]

Flattening out sublists and subarrays.

This generates a 2×3 array:

Array[a,{2,3}]

(RefLink[Flatten, paclet:ref/Flatten]) in effect puts elements in lexicographic order of their indices:

Flatten[%]

This creates a matrix from a block matrix:

ArrayFlatten[{{{{1}},{{2,3}}},{{{4},{7}},{{5,6},{8,9}}}}]

Transposing levels in nested lists.

This generates a 2×2×2 array:

Array[a,{2,2,2}]

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

Transpose[%,{3,1,2}]

This restores the original array:

Transpose[%,{2,3,1}]

Applying functions in nested lists.

Here is a nested list:

m={{{a,b},{c,d}},{{e,f},{g,h},{i}}};

This maps a function f at level 2:

Map[f,m,{2}]

This applies the function at level 2:

Apply[f,m,{2}]

This applies f to both parts and their indices:

MapIndexed[f,m,{2}]

Operations on nested lists.

Here is a nested list:

m={{{a,b,c},{d,e}},{{f,g},{h},{i}}};

This rotates different amounts at each level:

RotateLeft[m,{0,1,-1}]

This pads with zeros to make a 2×3×3 array:

PadRight[%,{2,3,3}]