Thread Part ([[]]) over two lists
To understand what is going on here let's do the same evaluation with a symbol with no value and monitor it with Trace
:
Remove[f];
Thread[f[lst1, indices]] // Trace
(*
{{{lst1, {{5,-9,15}, {12,-15,4}}}, {indices, {{2,1,3}, {1,3,2}}},
f[{{5,-9,15},{12,-15,4}}, {{2,1,3}, {1,3,2}}]}, Thread[f[{{5,-9,15},
{12,-15,4}}, {{2,1,3},{1,3,2}}]], {f[{5,-9,15}, {2,1,3}], f[{12,-15,4}, {1,3,2}]}}
*)
Here we see that indices
was evaluated before being passed to f
, so the error occurs before Thread
gets its inputs. Now replace f
with Part
and you see the reason for the error. Part
does not accept a list of lists as input only a 1D list is supported. To get around this, you can temporarily make Part
inactive, do the evaluation then activate it as follows:
Thread[Inactive[Part][lst1, indices]] // Activate
{{-9, 5, 15}, {12, 4, -15}}
as expected with no error messages. There are other ways to achieve the same thing, we can use f
as described and later replace f
with Part
.
RunnyKine already explained in detail the source of the message. I would like to offer a couple of alternative formulations of a solution and comment on your attempt to use Hold
.
You commented:
I tried
Thread[Hold[Part[lst1,indices]]]//ReleaseHold
. Apparently placedHold
at wrong place.
Indeed, for two reasons.
In this expression
Hold
is the active head of the argument ofThread
so, if it were possible, it is the head that would be distributed:Thread[Hold[{1, 2, 3}]]
{Hold[1], Hold[2], Hold[3]}
For
Thread
to operate it must see explicit arguments at second level of the expression.Hold
here preventslst1
andindices
from evaluating to their full forms therefore even if (1) is solved a problem remains. To illustrate this we can useUnevaluated
which is like a temporaryHold
that prevents evaluation but is transparent to the function in which it appears, i.e.Thread
:Thread[Unevaluated[Part[lst1, indices]]] (* Part::pkspec1 printed *)
RunnyKine's use of Inactive
and andre's use of Hold[Part]
each get around both these problems because:
They do not introduce an additional level in the expression;
Hold[Part]
is a compound head.TreeForm /@ {Hold[head[1, 2]], Hold[head][1, 2]}
While
Part
is rendered inactive the arguments of the compound head still evaluate in the default manner thereforelst1
andindices
are expanded.
Another way to temporarily inactivate Part
is Block
:
Block[{Part}, Thread @ lst1[[indices]] ]
But as already demonstrated by ciao (rasher) this kind of inhibition is not needed as MapThread
allows exactly the evaluation you want: expansion of lst1
and indices
before Part
is applied and evaluated.