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

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]


This inserts x so that it becomes element number 2.

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


This replaces the third element in the list with x.

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


This replaces the element in a matrix.

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


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}


This sets the third element to be x.

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


Now v has been changed.

In[7]:= v


Resetting pieces of matrices.

This defines m to be a matrix.

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


This sets the first column of the matrix.

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


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

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