12.9 Grouping and Ungrouping Elements of Lists
Functions for grouping and ungrouping elements of lists.
Here is a list.
In[1]:= t = {a, b, c, d, e, f, g};
This groups the elements of the list in pairs, and in this case throws away the single element that is left at the end.
In[2]:= Partition[t, 2]
Out[2]=
This groups elements in triples. There is no overlap between the triples.
In[3]:= Partition[t, 3]
Out[3]=
This makes triples of elements, with each successive triple offset by just one element.
In[4]:= Partition[t, 3, 1]
Out[4]=
Here is a triply nested array.
In[5]:= u = {{{a, b}, {c, d}}, {{e, f}, {g, h}}};
This "flattens out" sublists. You can think of it as effectively removing the inner sets of braces.
In[6]:= Flatten[u]
Out[6]=
This flattens only the first level of sublists.
In[7]:= Flatten[u, 1]
Out[7]=
This flattens each sublist on the first level.
In[8]:= Map[Flatten, u]
Out[8]=
You should realize that because of the way Mathematica TE stores lists, it is usually less efficient to add a sequence of elements to a particular list than to create a nested structure that consists, for example, of lists of length 2 at each level. When you have built up such a structure, you can always reduce it to a single list using Flatten.
This sets up a nested list structure for w.
In[9]:= w = {0}; Do[ w = {w, k^2}, {k, 1, 4} ]; w
Out[9]=
You can use Flatten to unravel the structure.
In[10]:= Flatten[w]
Out[10]=
Other Mathematica functions related to lists. (See Section 3.2.)