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. | |
Out[2]=
|
|
| This gives the third element. | |
Out[3]=
|
|
| This gives a list of the first and fourth elements. | |
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. | |
Out[5]=
|
|
| This gives the last three elements. | |
Out[6]=
|
|
| This gives elements 2 through 5 inclusive. | |
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. | |
Out[9]=
|
|
| This gives t with its first three elements dropped. | |
Out[10]=
|
|
| This gives t with only its third element dropped. | |
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.
|