Level

Lots of examples using Level can be found in the discussion of Level Specification. Below I explain some of the subtle details.

In the next cell we get  a list of all subexpressions at level 2 in expr.  Notice x1 and  x7  each  appear twice in expr and twice in the result returned by Level.

ClearAll["Global`*"] ;  expr = {g[x1], {x1, x2}, {x3, x4}, g[x6], h[1][x7], g[x7]} ;  Level[expr, {2}]

{x1, x1, x2, x3, x4, x6, x7, x7}


It seems Level gives a result such that the elements are sorted according to
their position in the original expression.  This is demonstrated in the next
cell where a sorted list of positions is used to get the same result we got
above and the positions are in canonical order.  Notice each list of
positions has length 2 and this is what we expect since we asked for all
expressions at level 2.

posn = Sort[{{1, 1}, {2, 1}, {2, 2}, {3, 1}, {3, 2}, {4, 1}, {5, 1}, {6, 1}}] ;    Extract[expr, posn]

{x1, x1, x2, x3, x4, x6, x7, x7}

Heads Option


By default Level uses the setting (Heads→False).  In the next cell we
use (Heads→True) and get the heads at level 2.

Level[expr, {2}, HeadsTrue]

{g, x1, List, x1, x2, List, x3, x4, g, x6, h[1], x7, g, x7}

Using the third argument in Level


Finally Level can be given a third argument that can be applied to the list
returned.  To demonstrate this feature consider the next cell which gives a
list of all subexpressions at level 3 and deeper.

demo = x + Cos[(π (2 + x/3)^(1/2))/3] + Sin[(πx^(1/2))/6] ;  Level[demo, {3, ∞}]

{1/3, π, 2, 1/3, x, x/3, 2 + x/3, 1/2, (2 + x/3)^(1/2), 1/6, π, x, 1/2, x^(1/2)}


In the next cell Level returns the sum of the elements we got from the
previous cell.

Level[demo, {3, ∞}, Plus]

35/6 + 2 π + (2 + x/3)^(1/2) + x^(1/2) + (8 x)/3


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page