# Levels in Expressions

The Part function allows you to access specific parts of Wolfram Language 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 Wolfram Language expressions. Many Wolfram Language 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:= Out//TreeForm= This searches for x in the expression t down to level 1. It finds only one occurrence:
 In:= Out= This searches down to level 2. Now it finds both occurrences of x:
 In:= Out= This searches only at level 2. It finds just one occurrence of x:
 In:= Out= 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 {n1,n2} levels n1 through n2 Heads->True include heads Heads->False exclude heads

Level specifications.

Here is an expression, displayed in tree form:
 In:= Out//TreeForm= This searches for a at levels from 2 downward:
 In:= Out= This shows where f appears other than in the head of an expression:
 In:= Out= This includes occurrences of f in heads of expressions:
 In:= Out= 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 u that occur down to level 2:
 In:= Out= Here are the parts specifically at level 2:
 In:= Out= 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 -1:
 In:= Out= 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 g[a] is 2:
 In:= Out= The parts of u at level -2 are those that have depth exactly 2:
 In:= Out= 