Extract subscript of variable in product

My input is a product of the variable x with index:

x[1]^2 x[5] x[7]


How do I extract the indices of the above product to get the list {1,1,5,7} as an output? Note 1 appears twice in the list since x[1] is squared.

I would like this code to work for any product of x[j]^n, where both j and n will be given integers.

• Cases[expr, x[i_]^p_. :> Table[i, p], {1}] // Flatten Commented May 16, 2021 at 0:53
• Thank you @BobHanlon. Your solution is simple -- do you want to submit your comment as an answer? Commented May 16, 2021 at 1:42
• Just wanted to say: good job avoiding Subscript and using indexed variables instead! This is the way to go! :) Commented May 17, 2021 at 7:49

expr = x[1]^2 x[5] x[7];


Use Cases and include Default in the pattern for the exponent.

sol = Cases[expr, x[i_]^p_. :> Table[i, p], {1}] // Flatten

(* {1, 1, 5, 7} *)


Here is one way to achieve it, decomposed step by step:

ClearAll[x];
p = x[1]^2 x[5] x[7];
f = FactorList@p
Table[First@#, Last@#] & /@ Rest[f]
Flatten@%
Block[{x = # &}, %]
(*
{{1, 1}, {x[1], 2}, {x[5], 1}, {x[7], 1}}
{{x[1], x[1]}, {x[5]}, {x[7]}}
{x[1], x[1], x[5], x[7]}
{1, 1, 5, 7}
*)


(there may be a better way of extracting i from x[i]...)