This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)
 Documentation / Mathematica / The Mathematica Book / Practical Introduction / Lists  /

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}


  • Here is the last element of t.
  • In[2]:= Last[t]


  • This gives the third element.
  • In[3]:= t[[3]]


  • This gives a list of the first and fourth elements.
  • In[4]:= t[[ {1, 4} ]]


    Picking out sequences in lists.

  • This gives the first three elements of the list t defined above.
  • In[5]:= Take[t, 3]


  • This gives the last three elements.
  • In[6]:= Take[t, -3]


  • This gives elements 2 through 5 inclusive.
  • In[7]:= Take[t, {2, 5}]


  • This gives t with the first element dropped.
  • In[8]:= Rest[t]


  • This gives t with its first three elements dropped.
  • In[9]:= Drop[t, 3]


  • This gives t with only its third element dropped.
  • In[10]:= Drop[t, {3, 3}]


    Extracting parts of nested lists.

  • Here is a list of lists.
  • In[11]:= t = {{a, b, c}, {d, e, f}}


  • This picks out the first sublist.
  • In[12]:= t[[1]]


  • This picks out the second element in the first sublist.
  • In[13]:= t[[1, 2]]


  • This is equivalent to t[[1,2]], but is clumsier to write.
  • In[14]:= t[[1]][[2]]


  • This gives a list containing two copies of the second part of t, followed by one copy of the first part.
  • In[15]:= t[[{2, 2, 1}]]


  • For each of the parts picked out on the previous line, this gives a list of their second and third parts.
  • In[16]:= t[[{2, 2, 1}, {2, 3}]]


    Another way to extract parts of nested lists.

  • This extracts the element at position {2,1} in t.
  • In[17]:= Extract[t, {2, 1}]


  • This extracts a list of three elements from t.
  • In[18]:= Extract[t, {{1, 1}, {2, 2}, {2, 3}}]


    Section 2.1.5 will show 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 will show 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.