ReplacePart

ReplacePart[expr,inew]

yields an expression in which the i ^(th) part of expr is replaced by new.

ReplacePart[expr,{i1new1,i2new2,}]

replaces parts at positions in by newn.

ReplacePart[expr,{i,j,}new]

replaces the part at position {i,j,}.

ReplacePart[expr,{{i1,j1,}new1,}]

replaces parts at positions {in,jn,} by newn.

ReplacePart[expr,{{i1,j1,},}new]

replaces all parts at positions {in,jn,} by new.

ReplacePart[inew]

represents an operator form of ReplacePart that can be applied to an expression.

Details and Options

  • Explicit negative part numbers count from the end. »
  • Part position specifications can be patterns.
  • Each pattern is effectively tested against each list of part numbers for parts in expr.
  • Patterns p (such as x_) that are not explicitly lists are treated as {p}.
  • Patterns can include constructs such as __, representing position specifications of variable lengths.
  • ReplacePart[expr,i:>new] can be used to replace a part without first evaluating it. With a rule such as patt:>new, new is evaluated separately for each position that matches patt.
  • With the default option setting Heads->Automatic, a head is replaced only when the corresponding position specification is explicitly 0.
  • With Heads->True a head is replaced whenever the corresponding position specification matches 0.
  • Heads->False never replaces heads.
  • ReplacePart can be used on SparseArray objects.
  • ReplacePart[i->new]][expr] is equivalent to ReplacePart[expr,i->new].

Examples

open allclose all

Basic Examples  (6)

Replace part 3:

In[1]:=
Click for copyable input
Out[1]=

Replace parts 2 and 5:

In[1]:=
Click for copyable input
Out[1]=

Replace part {2,1} of an array:

In[1]:=
Click for copyable input
Out[1]=

Replace parts whose positions match a pattern:

In[1]:=
Click for copyable input
Out[1]=

Replace parts in any expression:

In[1]:=
Click for copyable input
Out[1]=

Use a ReplacePart operator:

In[1]:=
Click for copyable input
Out[1]=

Scope  (11)

Generalizations & Extensions  (4)

Options  (3)

Applications  (8)

Properties & Relations  (5)

Possible Issues  (4)

See Also

Part  Set  Extract  MapAt  FlattenAt  SparseArray  Insert  Delete  Sequence  StringReplacePart  BitSet

Tutorials

Introduced in 1991
(2.0)
| Updated in 2014
(10.0)