2.1.7 Levels in Expressions
The Part function allows you to access specific parts of Mathematica expressions. But particularly when your expressions have fairly uniform structure, it is often convenient to be able to refer to a whole collection of parts at the same time.
Levels provide a general way of specifying collections of parts in Mathematica expressions. Many Mathematica functions allow you to specify the levels in an expression on which they should act.
Here is a simple expression, displayed in tree form.
In[1]:= (t = {x, {x, y}, y}) // TreeForm
Out[1]//TreeForm=
This searches for x in the expression t down to level 1. It finds only one occurrence.
In[2]:= Position[t, x, 1]
Out[2]=
This searches down to level 2. Now it finds both occurrences of x.
In[3]:= Position[t, x, 2]
Out[3]=
This searches only at level 2. It finds just one occurrence of x.
In[4]:= Position[t, x, {2}]
Out[4]=
Controlling Position using levels.
You can think of levels in expressions in terms of trees. The level of a particular part in an expression is simply the distance down the tree at which that part appears, with the top of the tree considered as level 0.
It is equivalent to say that the parts which appear at level n are those that can be specified by a sequence of exactly n indices.
Level specifications.
Here is an expression, displayed in tree form.
In[5]:= (u = f[f[g[a], a], a, h[a], f]) // TreeForm
Out[5]//TreeForm=
This searches for a at levels from 2 downwards.
In[6]:= Position[u, a, {2, Infinity}]
Out[6]=
This shows where f appears other than in the head of an expression.
In[7]:= Position[u, f, Heads>False]
Out[7]=
This includes occurrences of f in heads of expressions.
In[8]:= Position[u, f, Heads>True]
Out[8]=
Testing and extracting levels.
This gives a list of all parts of u that occur down to level 2.
In[9]:= Level[u, 2]
Out[9]=
Here are the parts specifically at level 2.
In[10]:= Level[u, {2}]
Out[10]=
When you have got the hang of ordinary levels, you can try thinking about negative levels. Negative levels label parts of expressions starting at the bottom of the tree. Level 1 contains all the leaves of the tree: objects like symbols and numbers.
This shows the parts of u at level .
In[11]:= Level[u, {1}]
Out[11]=
You can think of expressions as having a "depth", which is equal to the maximum number of levels shown by TreeForm. In general, level n in an expression is defined to consist of all subexpressions whose depth is n.
The depth of g[a] is 2.
In[12]:= Depth[ g[a] ]
Out[12]=
The parts of u at level are those that have depth exactly 2.
In[13]:= Level[u, {2}]
Out[13]=
