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
Riffle[list,element]interleave element between the entries of list
Delete[list,i]delete the element at position i in list
ReplacePart[list,i->new]replace the element at position i in list with new
ReplacePart[list,{i,j}->new]replace with new

Functions for manipulating elements in explicit lists.

This gives a list with prepended.
In[1]:=
Click for copyable input
Out[1]=
This inserts so that it becomes element number 2.
In[2]:=
Click for copyable input
Out[2]=
This interleaves between the entries of the list.
In[3]:=
Click for copyable input
Out[3]=
This replaces the third element in the list with .
In[4]:=
Click for copyable input
Out[4]=
This replaces the 1, 2 element in a 2×2 matrix.
In[5]:=
Click for copyable input
Out[5]=

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={e1,e2,...}assign a variable to be a list
v[[i]]=newassign a new value to the i^(th) element

Resetting list elements.

This defines to be a list.
In[6]:=
Click for copyable input
Out[6]=
This sets the third element to be .
In[7]:=
Click for copyable input
Out[7]=
Now has been changed.
In[8]:=
Click for copyable input
Out[8]=
m[[i,j]]=newreplace the ^(th) element of a matrix
m[[i]]=newreplace the i^(th) row
m[[All,i]]=newreplace the i^(th) column

Resetting pieces of matrices.

This defines to be a matrix.
In[9]:=
Click for copyable input
Out[9]=
This sets the first column of the matrix.
In[10]:=
Click for copyable input
Out[10]=
This sets every element in the first column to be .
In[11]:=
Click for copyable input
Out[11]=
New to Mathematica? Find your learning path »
Have a question? Ask support »