# Recovering indices from an expression

I have a long list and one element in that list is:

U[1, 3] U[1, 4] U[1, 5] U[2, 2] U[3, 1]

All entries of the list have the same structure of products of U[i,j]'s. In the current instance this is a product of 5 terms but it could be a product of n terms.

Is there a way to extract from the "monomial" U[1, 3]U[1, 4]U[1, 5]U[2, 2]U[3, 1] the first entries (1,1,1,2,3) and the second entries (3,4,5,2,1) of each factor of the monomial?

Oh dear... I was working too hard. This will do it.

vars = Variables[U[1, 3] U[1, 4] U[1, 5] U[2, 2] U[3, 1]];
firstindex = Table[vars[[q]][[1]], {q, 1,Length[vars]}];
secondindex = Table[vars[[q]][[2]], {q, 1, Length[vars]}]

• firstindex = vars[[All, 1]] is even simpler. Commented May 22 at 14:55
• @SjoerdSmit yeah even simpler. Thanks. Commented May 23 at 1:08

For

expr = U[1, 3] U[1, 4] U[1, 5] U[2, 2] U[3, 1];


you can do

{firstindex, secondindex} = Transpose[List @@@ List @@ expr]


or

{firstindex, secondindex} = expr /. {Times -> List, U -> List} // Transpose


Given,

expression = U[1, 3]  U[1, 4]  U[1, 5]  U[2, 2]  U[3, 1]


you could use Cases:

Cases[expression, U[a_, b_] :> {a, b}]
(* {{1, 3}, {1, 4}, {1, 5}, {2, 2}, {3, 1}} *)


or

Cases[expression, mono_U :> List @@ mono]
(* {{1, 3}, {1, 4}, {1, 5}, {2, 2}, {3, 1}} *)


That gives you both idices simultaneously, but it should be obvious how to adapt that to just one or the other if that's really what you want.

• thanks. I can see how this would be very useful. Commented May 23 at 9:52