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

1.8.6 Adding, Removing and Modifying List Elements

Prepend[list, element] add element at the beginning of list
Append[list, element] add element at the end of list
Insert[list, element, i] insert element at position i in list
Insert[list, element, -i] insert at position i counting from the end of list
Delete[list, i] delete the element at position i in list
ReplacePart[list, new, i] replace the element at position i in list with new
ReplacePart[list, new, {i, j}] replace list[[i, j]] with new

Functions for manipulating elements in explicit lists.
This gives a list with x prepended.

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

Out[1]=

This inserts x so that it becomes element number 2.

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

Out[2]=

This replaces the third element in the list with x.

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

Out[3]=

This replaces the  element in a  matrix.

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

Out[4]=

Functions like ReplacePart take explicit lists and give you new lists. Sometimes, however, you may want to modify a list "in place", without explicitly generating a new list.

v = { ,  , ... } assign a variable to be a list
v[[i]] = new assign a new value to the i element

Resetting list elements.
This defines v to be a list.

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

Out[5]=

This sets the third element to be x.

In[6]:=  v[[3]] = x

Out[6]=

Now v has been changed.

In[7]:=  v

Out[7]=

m[[i, j]] = new replace the   element of a matrix
m[[i]] = new replace the i row
m[[All, i]] = new replace the i column

Resetting pieces of matrices.
This defines m to be a matrix.

In[8]:=  m = {{a, b}, {c, d}}

Out[8]=

This sets the first column of the matrix.

In[9]:=  m[[All, 1]] = {x, y}; m

Out[9]=

This sets every element in the first column to be 0.

In[10]:=  m[[All, 1]] = 0; m

Out[10]=



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.