Skip to main content

syntax - Error when using rule as a list index - { i, x[[i]] } /. i -> 5


I can't seem to use a rule to index a vector.


x = Range[10];
{ i, x[[i]] } /. i -> 5

I get the following error when evaluating the above code, even if the next cell shows the correct result:


Part::pspec: Part specification i is neither an integer nor a list of integers.


Answer



Using Trace,


Trace[x = Range[10]; { i, x[[i]] } /. i -> 5]

we will see that the error comes from Mathematica trying to evaluate


{1,2,3,4,5,6,7,8,9,10}[[i]]

As you pointed out, the error message is harmless in this case. If you want Mathematica to substitute first, you can use Hold and ReleaseHold:


x = Range[10];
ReleaseHold[Hold[{i, x[[i]]}] /. i -> 5]


which prevents the evaluation of {i, x[[i]]} until the Hold is released. The output is the same, but now without the error message:



{5,5}



Comments