# How to replace all occurrences of an element in a list?

Consider the following:

list={1,2,2,2,3};


I would like to replace all 2 with the string "Test". Replace[list,2->"Test"] does not do it.

Result must be: {1,"Test","Test","Test",3}.

-

You can use:

list /. {2 -> "Test"}

(* Out[]:= {1, "Test", "Test", "Test", 3} *)

-
Internally, a /. b becomes ReplaceAll[a,b] which by default, replaces all instances found. –  rcollyer Apr 19 '12 at 17:00
I prefere this one at the moment, as you can replace different figures at the same time, e.g. list/.{1->"A",2->"X"}. I wounder whether Replace is able of that too? –  John Apr 19 '12 at 17:01
@John It is: Replace[list, {1 -> "B", 2 -> "Test"}, {1}] –  Eli Lansey Apr 19 '12 at 17:02
@John note, that once a match is found, it stops looking, and refuses to apply a sequence of replacements, e.g. a /. {a -> b, b -> c} returns b. But, you can use ReplaceRepeated (//.), instead. a //. {a -> b, b -> c} then returns c. –  rcollyer Apr 19 '12 at 17:05

Replace by default works on the whole expression. You can add a level specification

list={1,2,2,2,3};
Replace[list,2->"Test", {1}]


Gives

{1, "Test", "Test", "Test", 3}

-

For example:

list = {1, 2, 2, 2, 3};
list /. {2 -> "test"}
If[# == 2, "test", #] & /@ list
Replace[list, 2 -> "test", 1]
ReplacePart[list, Position[list, 2] -> "test"]

-