Mathematica 9 is now available
Previous section-----Next section

1.8.4 Getting Pieces of Lists

First[list] the first element in list
Last[list] the last element
Part[list, n] or list[[n]] the n element
Part[list, -n] or list[[-n]] the n element from the end
Part[list, { ,  , ... }] or list[[{ ,  , ... }]]
the list of elements at positions  ,  , ...

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]=

Take[list, n] the first n elements in list
Take[list, -n] the last n elements
Take[list, {m, n}] elements m through n (inclusive)
Rest[list] list with its first element dropped
Drop[list, n] list with its first n elements dropped
Most[list] list with its last element dropped
Drop[list, -n] list with its last n elements dropped
Drop[list, {m, n}] list with elements m through n dropped

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]=

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.



Any questions about topics on this page? Click here to get an individual response.Buy NowMore Information
THIS IS DOCUMENTATION FOR AN OBSOLETE PRODUCT.
SEE THE DOCUMENTATION CENTER FOR THE LATEST INFORMATION.