# Get subscripts of sum of expression and save each summand's subscript separately

I deal with expressions like

A= a_i a_j a_k + a_i a_l a_m+ ...


where the a_i notation is shorthand for Subscript["a",i] and all subscripts are integers. In this example each summand has 3 terms but in general it can have an arbitrary length. In the end I want to have something like

{{i,j,k},{i,l,m},...}


Using

A /. Plus -> List


I managed to separate the summands into list entries

B = {a_i a_j a_k, a_i a_l a_m,...}


and by the replacement rule

C= B /. {Subscript[a_,n_] :> ToString[n]}

C = {i j k, i l m,...}


where I needed the ToString command because otherwise Mathematica evaluates the product i j k to a number.

I am now looking for a way to get the

list={{i,j,k},{i,l,m},...}


output where all variables are treated as numbers again, so I can use them later to access their corresponding elements of some other list.

I appreciate any kind of help as I am not so fluent in Mathematica yet.

• how about A /. Plus|Times -> List /. Subscript[x_, y_]:>y?
– kglr
Jul 31 '19 at 15:20

SeedRandom
expr = Plus @@ Times @@@ Map[Subscript[a, #]&, Table[RandomSample[Range@9, 3], {5}], {-1}]

TeXForm @ expr


$$a_4 a_6 a_7+a_3 a_4 a_8+a_4 a_6 a_8+a_3 a_5 a_9+a_1 a_8 a_9$$

expr /. Plus | Times -> List /. Subscript -> (#2 &)


{{4, 6, 7}, {3, 4, 8}, {4, 6, 8}, {3, 5, 9}, {1, 8, 9}}

Alternatively,

Extract[#, Position[#, Subscript] /. 0 -> 2] & /@ (List @@ expr)


{{4, 6, 7}, {3, 4, 8}, {4, 6, 8}, {3, 5, 9}, {1, 8, 9}}