Legacy Documentation

Mathematica® Teacher's Edition (2002)

This is documentation for an obsolete product.
Current products and services
 Documentation /  Mathematica Teacher's Edition /  The Teacher's Book /  Interlude 1: Lists /

12.3 Getting Pieces of Lists

Picking out elements of lists.

The variable t will be defined as a 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 t with the first element dropped.

In[3]:= Rest[t]

Out[3]=

This gives the third element.

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

Out[4]=

This gives a list of the first and fourth elements.

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

Out[5]=

Picking out sequences in lists.

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

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

Out[6]=

This gives the last three elements.

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

Out[7]=

This gives elements 2 through 5 inclusive.

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

Out[8]=

This gives t with its first three elements dropped.

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

Out[9]=

This gives t with its last 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 sublist.

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

Out[14]=

This picks out the second element in the first sublist.

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

Out[15]=

This picks out the first element in the second sublist.

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

Out[16]=

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

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

Out[17]=

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

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

Out[18]=

The functions in this section allow you to pick out pieces that occur at particular positions in lists. Section 27.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.