# Take i'th element of a list

I have a list :

{{j1,j2,j3},{j4,j5,j6}}


I would like to take the 5'th element of this list that is composed of two sublist.

How to do that ?

Indeed j[[5]] returns an error as it thinks I want the 5'th sublist which doesn't exist.

I tried to find a similar topic but I didn't find it on this website.

I am a huge beginner in mathematica

• Flatten[list][[5]]? May 18, 2017 at 12:43
• Thank you but is there a more compact way to do it ? Because it would force me to create another variable if I want a compact expression. I am computing a sum and it would complexify the reading of it if I write Flatten[...]. And I would like to prevent multiple variable creations. But I am probably asking too much :o May 18, 2017 at 13:20
• I don't know what you mean by creating another variable...What about Flatten[j][[5]]? We basically have three symbols here, Flatten, j or list, and 5, which is just only symbol more complicated than j[[5]], which doesn't work. You could use j[[2, 2] to get j5, but that does not really fit how you have framed the problem. May 18, 2017 at 13:33
• Well ok it seems it is the only solution. What I meant is that I could write b=Flatten[j] And then use b[[5]] which is compact. May 18, 2017 at 13:34
• If you are looking for an equivalent of Matlab's indexing (where an n-dimensional array can be indexed by a single value, which treats the underlying array as a vector with Matlab's array ordering) you won't find an exact equivalent in Mathematica. Also, your comments about 'compact'-ness are somewhat odd for Mathematica: Mathematica is mostly an immutable functional language, so statements like Flatten[x][[i]] are quite common. It would be a mistake to assume that Flatten[x][[i]] is fundamentally slower than Matlab's x(i) --- it could be, but that depends on both implementations.
– nben
May 18, 2017 at 15:15

In:

xss = {{j1, j2, j3}, {j4, j5, j6}};
{m, n} = QuotientRemainder[5, 3];
xss[[m + 1]][[n]]


Out:

j5


Deeper? Tensor?

In:

{u, v, w} = {3, 4, 5};
xss = Array[Subscript[x, {#1, #2, #3}] &, {u, v, w}];
Clear[f, m, n, o];
f[m_, n_, o_] := (m - 1) v w + (n - 1) w + o
xss /. Subscript[x, {m_, n_, o_}] -> {f[m, n, o],
Subscript[x, {m, n, o}]} // MatrixForm


Out:

Or

In:

Clear[f, x, m, n, o, rules];
SeedRandom[1]
{u, v, w} = {3, 4, 5};
xss = Array[Subscript[x, {#1, #2, #3}] &, {u, v, w}];
f[m_, n_, o_] := (m - 1) v w + (n - 1) w + o
rules = MapIndexed[Rule[f[Sequence @@ #2], #2] &, xss, {3}]  // Flatten

{m, n, o} = 6 /. rules
xss[[m]][[n]][[o]]


Out:

{1, 2, 1}

• Can you generalize this to deeper arrays? May 18, 2017 at 16:03
• @Mr.Wizard probably ;) May 18, 2017 at 17:03

If the size of the list is fixed you could make a lookup table of positions to extract:

L = {{j1, j2, j3}, {j4, j5, j6}};
lookup = Position[L, _, {Length[Dimensions[L]]}, Heads -> False];
part[x_] := Extract[L, lookup[[x]]]

part[{2, 3, 6}]


{j2, j3, j6}