# How to write an element of a nested list whose index is given by the elements of another list

This is purely a list manipulation question. I have a simple non-nested list of positive integers of length m say (where m could be large):

t={t1,...,tm}


I have another nested list s which is m times nested so s represents a rank m tensor e.g. when m=2, s represents a matrix. How do I write the following

s[[t1]]...[[tm]]


in simple closed form (i.e. without ellipses)? Thanks in advance for any help.

• Should be s[[t]]. Aug 27 '19 at 13:35
• So you mean that s has m indices, right? So basically you want s[[t1, t2, t3, ..., tm]] if I understand correctly. That could be achieved by s[[Sequence @@ t]] or Extract[s, t] Aug 27 '19 at 14:05

Here's a simple concrete example with a rank-3 tensor:

In[19]:= s = RandomReal[1, {5, 6, 7}];
Dimensions[s]
TensorRank[s]

Out[20]= {5, 6, 7}

Out[21]= 3


Extracting the element at position {3, 1, 2} can be done by repeatedly taking a Part ([[...]]) each level down, but it's easier to just use a single Part spec:

In[35]:= s[[3]][[1]][[2]]
s[[3, 1, 2]]

Out[35]= 0.350807

Out[36]= 0.350807


If you have the position stored in a variable, you can use Sequence to splice it into the Part brackets or you can use extract:

In[26]:= t = {3, 1, 2};
s[[Sequence @@ t]]
Extract[s, t]

Out[27]= 0.350807

Out[28]= 0.350807


If you really want to use repeated parts (which is probably not a good idea, but just for purposes of illustration), you can use Fold, to repeatedly extract the next level of the tensor. This is equivalent to s[[3]][[1]][[2]]:

In[32]:= Fold[#1[[#2]] &, s, t]

Out[32]= 0.350807