Mathematica 9 is now available
 Documentation /  Mathematica /  The Mathematica Book /  A Practical Introduction to Mathematica /  Lists /

Testing and Searching List ElementsCombining Lists

1.8.6 Adding, Removing and Modifying List Elements

Functions for adding and deleting elements in lists.

This gives a list with x prepended.

In[1]:= Prepend[{a, b, c}, x]

Out[1]=

This adds x at the end.

In[2]:= Append[{a, b, c}, x]

Out[2]=

This inserts x so that it becomes element number 2.

In[3]:= Insert[{a, b, c}, x, 2]

Out[3]=

Negative numbers count from the end of the list.

In[4]:= Insert[{a, b, c}, x, -2]

Out[4]=

Delete removes an element from the list.

In[5]:= Delete[{a, b, c, d}, 3]

Out[5]=

Modifying parts of lists.

This replaces the third element in the list with x.

In[6]:= ReplacePart[{a, b, c, d}, x, 3]

Out[6]=

This replaces the first and fourth parts of the list. Notice the need for double lists in specifying multiple parts to replace.

In[7]:= ReplacePart[{a, b, c, d}, x, {{1}, {4}}]

Out[7]=

Here is a identity matrix.

In[8]:= IdentityMatrix[3]

Out[8]=

This replaces the component of the matrix by x.

In[9]:= ReplacePart[%, x, {2, 2}]

Out[9]=

Padding lists.

This pads with zeros on the left to make a list of length 10.

In[10]:= PadLeft[{a, b, c}, 10]

Out[10]=

This pads with copies of the sequence x, y.

In[11]:= PadLeft[{a, b, c}, 10, {x, y}]

Out[11]=

This leaves a margin of 3 elements on the right.

In[12]:= PadLeft[{a, b, c}, 10, {x, y}, 3]

Out[12]=

Testing and Searching List ElementsCombining Lists



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.