This is documentation for Mathematica 5, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)

Documentation / Mathematica / The Mathematica Book / A Practical Introduction to Mathematica / Lists /

1.8.6 Adding, Removing and Modifying List Elements

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.

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

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