This is documentation for Mathematica 4, which was
based on an earlier version of the Wolfram Language.
Wolfram Research, Inc.

1.8.4 Getting Pieces of Lists

Picking out elements of lists.

We will use this list for the examples.

In[1]:= t = {a,b,c,d,e,f,g}

Out[1]=

Here is the last element of t.

In[2]:= Last[t]

Out[2]=

This gives the third element.

In[3]:= t[[3]]

Out[3]=

This gives a list of the first and fourth elements.

In[4]:= t[[ {1, 4} ]]

Out[4]=

Picking out sequences in lists.

This gives the first three elements of the list t defined above.

In[5]:= Take[t, 3]

Out[5]=

This gives the last three elements.

In[6]:= Take[t, -3]

Out[6]=

This gives elements 2 through 5 inclusive.

In[7]:= Take[t, {2, 5}]

Out[7]=

This gives elements 3 through 7 in steps of 2.

In[8]:= Take[t, {3, 7, 2}]

Out[8]=

This gives t with the first element dropped.

In[9]:= Rest[t]

Out[9]=

This gives t with its first three elements dropped.

In[10]:= Drop[t, 3]

Out[10]=

This gives t with only its third element dropped.

In[11]:= Drop[t, {3, 3}]

Out[11]=

Extracting parts of nested lists.

Here is a list of lists.

In[12]:= t = {{a, b, c}, {d, e, f}}

Out[12]=

This picks out the first sublist.

In[13]:= t[[1]]

Out[13]=

This picks out the second element in the first sublist.

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

Out[14]=

This is equivalent to t[[1, 2]], but is clumsier to write.

In[15]:= t[[1]][[2]]

Out[15]=

This gives a list containing two copies of the second part of t, followed by one copy of the first part.

In[16]:= t[[{2, 2, 1}]]

Out[16]=

For each of the parts picked out on the previous line, this gives a list of their second and third parts.

In[17]:= t[[{2, 2, 1}, {2, 3}]]

Out[17]=

This in effect gives the second column of t.

In[18]:= t[[All, 2]]

Out[18]=

This gives all the elements in the second and third columns.

In[19]:= t[[All, {2, 3}]]

Out[19]=

Another way to extract parts of nested lists.

This extracts the element at position {2, 1} in t.

In[20]:= Extract[t, {2, 1}]

Out[20]=

This extracts a list of three elements from t.

In[21]:= Extract[t, {{1, 1}, {2, 2}, {2, 3}}]

Out[21]=

Picking out blocks in nested lists.

Here is a matrix.

In[22]:= m = {{a, b, c}, {d, e, f}, {g, h, i}};

This extracts the bottom-right submatrix.

In[23]:= Take[m, {2, 3}, {2, 3}]

Out[23]=

This leaves only the top-left submatrix.

In[24]:= Drop[m, {2, 3}, {2, 3}]

Out[24]=

This gives the same result.

In[25]:= Drop[m, -2, -2]

Out[25]=

Section 2.1.5 shows how all the functions in this section can be generalized to work not only on lists, but on any Mathematica expressions.

The functions in this section allow you to pick out pieces that occur at particular positions in lists. Section 2.3.2 shows how you can use functions like Select and Cases to pick out elements of lists based not on their positions, but instead on their properties.