Wolfram Research, Inc.

2.1.4 Parts of Expressions

Since lists are just a particular kind of expression, it will come as no surprise that you can refer to parts of any expression much as you refer to parts of a list.

This gets the second element in the list {a, b, c}.

In[1]:= {a, b, c}[[2]]

Out[1]=

You can use the same method to get the second element in the sum x + y + z.

In[2]:= (x + y + z)[[2]]

Out[2]=

This gives the last element in the sum.

In[3]:= (x + y + z)[[-1]]

Out[3]=

Part 0 is the head.

In[4]:= (x + y + z)[[0]]

Out[4]=

You can refer to parts of an expression such as f[g[a], g[b]] just as you refer to parts of nested lists.

This is part 1.

In[5]:= f[g[a], g[b]] [[1]]

Out[5]=

This is part {1,1}.

In[6]:= f[g[a], g[b]] [[1, 1]]

Out[6]=

This extracts part {2,1} of the expression 1 + x^2.

In[7]:= (1 + x^2) [[2, 1]]

Out[7]=

To see what part is {2,1}, you can look at the full form of the expression.

In[8]:= FullForm[1 + x^2]

Out[8]//FullForm=

You should realize that the assignment of indices to parts of expressions is done on the basis of the internal Mathematica forms of the expression, as shown by FullForm. These forms do not always correspond directly with what you see printed out. This is particularly true for algebraic expressions, where Mathematica uses a standard internal form, but prints the expressions in special ways.

Here is the internal form of x / y.

In[9]:= FullForm[x / y]

Out[9]//FullForm=

It is the internal form that is used in specifying parts.

In[10]:= (x / y)[[2]]

Out[10]=

You can manipulate parts of expressions just as you manipulate parts of lists.

This replaces the third part of a + b + c + d by x^2. Note that the sum is automatically rearranged when the replacement is done.

In[11]:= ReplacePart[a + b + c + d, x^2, 3]

Out[11]=

Here is an expression.

In[12]:= t = 1 + (3 + x)^2 / y

Out[12]=

This is the full form of t.

In[13]:= FullForm[ t ]

Out[13]//FullForm=

This resets a part of the expression t.

In[14]:= t[[2, 1, 1]] = x

Out[14]=

Now the form of t has been changed.

In[15]:= t

Out[15]=

Functions for manipulating parts of expressions.

Section 1.2.4 discussed how you can use lists of indices to pick out several elements of a list at a time. You can use the same procedure to pick out several parts in an expression at a time.

This picks out elements 2 and 4 in the list, and gives a list of these elements.

In[16]:= {a, b, c, d, e}[[{2, 4}]]

Out[16]=

This picks out parts 2 and 4 of the sum, and gives a sum of these elements.

In[17]:= (a + b + c + d + e)[[{2, 4}]]

Out[17]=

Any part in an expression can be viewed as being an argument of some function. When you pick out several parts by giving a list of indices, the parts are combined using the same function as in the expression.