How to | Work with Nested Lists
Nested lists are lists within a list; they are the principal structure for data in the Wolfram Language 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:
alist = {{a1, a2, a3, a4}, {b1, b2, b3, b4}, {c1, c2, c3, c4}, {d1, d2, d3, d4}}Matrices in the Wolfram Language are represented as nested lists. Note that each row corresponds to a sublist in the nested list:
MatrixForm[alist]Use [[]], the short form of the Part function, to get the second row:
alist[[2]]alist[[2, 3]]alist[[All, 3]]Use Flatten to remove the nesting:
Flatten[alist]Display the flattened data as a column:
MatrixForm[Flatten[alist]]For comparison, to display the flattened data as a row, add {}:
MatrixForm[{Flatten[alist]}]You can operate on the individual sublists of a nested list or on the nested list as a whole.
data = Table[i + j, {i, 1, 5}, {j, 1, 4}]MatrixForm[data]Most functions map over each sublist within a nested list.
Create four plots from the rows in the dataset:
ListLinePlot[data, AxesOrigin -> {0, 0}]Most descriptive statistics functions operate by columns.
Mean[data]Get the mean of all the numbers by flattening the list:
Mean[Flatten[data]]