Iterate a variable n as a levelspec in Replace ?

In the fuction Replace[expr,rules,levelspec], levelspec may be a variable:
Given:

g = {{{a, b}}, {a, b}, c}
locVar = {a, b}
Replace[g, locVar -> 10, 1]

Here 1 is the levelspec, run Replace[g, locVar → 10, 1] will:

{{{a, b}}, 10, c};

run

Replace[g, locVar -> 10, 2] :
{{10}, 10, c}
Replace[g, locVar -> 10, n] /. n -> {1, 2}:
{{10}, 10, c}

But how to iterate n?
run

Do[Replace[g, locVar -> 10, n], {n, 1, 2}]

, no result,why?

Try Table[]:

In[1]:= g = {{{a, b}}, {a, b}, c};
locVar = {a, b};
Table[Replace[g, locVar -> 10, n], {n, 1, 2}]

Out[3]= {{{{a, b}}, 10, c}, {{10}, 10, c}}

Hi Yinsheng, if you want to apply Replace on multiple levels at once you can also specify levelspec as {a,b} such that is will replace on levels a to b. If you want to keep separate levels, use Valeriu’s answer.

Good? Got it by your answer!!Thanks!!!

Table[Replace[g, locVar → 10, {1, 2}]]
:{{10}, 10, c}

It’s OK? Appreciated?

If you don’t want to keep separate levels, then you can simply wright:

In[1]:= g = {{{a, b}}, {a, b}, c};
locVar = {a, b};
Replace[g, locVar -> 10, 2]

Out[3]= {{10}, 10, c}

that means rule application up to second level.

If the range of levelspec n is not determined, how to use Table[Replace[g, locVar → 10, n], {n, 1, 2}]? I.e., Here, the maximum 2 is known as a constant, if it not known to be fixed, how to iterate Replace even in Table function?

To be more illustrative, I modify the initial example:

In[1]:= g = {{{{{{{a, b}}}}}}, {{{{a, b}}}}, {{{a, b}}}, {{a, b}}, {a, b}, c};
locVar = {a, b};
Table[Replace[g, locVar -> 10, n], {n, 1, Depth[g]}]

Out[1]= {{{{{{{{a, b}}}}}}, {{{{a, b}}}}, {{{a, b}}}, {{a, b}}, 10, c},
{{{{{{{a, b}}}}}}, {{{{a, b}}}}, {{{a, b}}}, {10}, 10, c},
{{{{{{{a, b}}}}}}, {{{{a, b}}}}, {{10}}, {10}, 10, c},
{{{{{{{a, b}}}}}}, {{{10}}}, {{10}}, {10}, 10, c},
{{{{{{{a, b}}}}}}, {{{10}}}, {{10}}, {10}, 10, c},
{{{{{{10}}}}}, {{{10}}}, {{10}}, {10}, 10, c},
{{{{{{10}}}}}, {{{10}}}, {{10}}, {10}, 10, c},
{{{{{{10}}}}}, {{{10}}}, {{10}}, {10}, 10, c}}

Excellent! You are really smart! :slight_smile: