Flatten

The basic use of Flatten is demonstrated in the next cell.  Lots of users know about the basic use of Flatten, but there is much more to the story.

Flatten[{{1, {2, {3, 4}}, 5, {6}}}]

{1, 2, 3, 4, 5, 6}

First of all Flatten will flatten nested layers of any head as demonsrated in the next cell.

Flatten[h[h[1, h[2, h[3, 4]], 5, h[6]]]]

h[1, 2, 3, 4, 5, 6]

When Flatten is given only one argument, it checks the head of the expression and flattens nested layers of that head.  Notice the nested lists in the next example aren't flattened.  Also in  this example we are flattening layers of (h), starting with the arguments of (expr) and going down to deeper levels.  When Flatten gets to a subexpression that doesn't have the head (h) it decides not to look inside this subexpression for nested layers of (h).  Hence the output has nested layers of (h) in {h[h[7],h[8]]}.

expr = h[h[1, h[2, h[3, 4]], 5, h[6]], {h[h[h[7]], h[8]]}, {9, {10}, {11, {12}, 13}}] ; Flatten[expr]

h[1, 2, 3, 4, 5, 6, {h[h[h[7]], h[8]]}, {9, {10}, {11, {12}, 13}}]

In the next input we give Flatten (2) as a second argument and only two layers of (h) are flattened.  Here too the subexpression g[h[8,h[9,10]]] doesn't have the head (h), so Flatten doesn't flatten layers of (h) in this subexpression.

expr = h[1, 2, h[3, h[4, h[h[h[5]], 6], g[h[8, h[9, 10]]]]]] ; Flatten[expr, 2]

h[1, 2, 3, 4, h[h[h[5]], 6], g[h[8, h[9, 10]]]]

We can give Flatten a third argument to indicate that layers with a certain head should be flattened. This is needed in the next cell to ensure layers of (h) are flattened.  If Flatten was given one or two arguments it would try to flatten layers of (g).

expr = g[1, h[2, h[3, 4, h[5, h[6, h[7, h[8]]]]]]] ; Flatten[expr, ∞, h]

g[1, 2, 3, 4, 5, 6, 7, 8]

In the next example Flatten is trying to flatten layers of (h).  Flatten finds that the subexpression g[h[9,h[10,11]]] doesn't have the head (h) so it doesn't flatten layers of (h) in that subexpression.

expr = g[1, h[2, h[3, 4, h[5, h[6, h[7, h[8]]]]]], g[h[9, h[10, 11]]]] ; Flatten[expr, ∞, h]

g[1, 2, 3, 4, 5, 6, 7, 8, g[h[9, h[10, 11]]]]

If we want to flatten all nested layers of (h), the replacement rule in the next cell should be used.

expr = g[1, h[2, h[3, 4, h[5, h[6, h[7, h[8]]]]]], g[h[9, h[10, 11]]]] ; expr//.h[e1___, h[e2___], e3___] :>h[e1, e2, e3]

g[1, h[2, 3, 4, 5, 6, 7, 8], g[h[9, 10, 11]]]


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page