# 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.

Out[1]//TreeForm= |

| |

This searches for

in the expression

down to level 1. It finds only one occurrence.

Out[2]= | |

This searches down to level 2. Now it finds both occurrences of

.

Out[3]= | |

This searches only at level 2. It finds just one occurrence of

.

Out[4]= | |

Position[expr,form,n] | give the positions at which form occurs in expr down to level n |

Position[expr,form,{n}] | give the positions exactly at level n |

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.

n | levels 1 through n |

Infinity | all levels (except 0) |

{n} | level n only |

{n_{1},n_{2}} | levels through |

Heads->True | include heads |

Heads->False | exclude heads |

Level specifications.

Here is an expression, displayed in tree form.

Out[5]//TreeForm= |

| |

This searches for

at levels from 2 downward.

Out[6]= | |

This shows where

appears other than in the head of an expression.

Out[7]= | |

This includes occurrences of

in heads of expressions.

Out[8]= | |

Level[expr,lev] | a list of the parts of expr at the levels specified by lev |

Depth[expr] | the total number of levels in expr |

Testing and extracting levels.

This gives a list of all parts of

that occur down to level 2.

Out[9]= | |

Here are the parts specifically at level 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

at level -1.

Out[11]= | |

You can think of expressions as having a "depth", as shown by TreeForm. In general, level -n in an expression is defined to consist of all subexpressions whose depth is n.

The depth of

is 2.

Out[12]= | |

The parts of

at level -2 are those that have depth exactly 2.

Out[13]= | |