# Multiply equations in lists

list = {x + 1, x - 3, {x - i, x + i}}


The last two elements should be multiplied. Desired output is:

{x + 1, x - 3, x^2 + 1}


I tried to no avail:

Apply[Times, list, 2]

• Look up MapAt[]; combine with Apply[]. – J. M.'s discontentment Oct 29 '15 at 12:35
• Ok, but I don't want to specify the specific place. I may have very different lists, so I am looking for a general rule. – GambitSquared Oct 29 '15 at 12:41
• ...then you might want to use Position[] also. – J. M.'s discontentment Oct 29 '15 at 12:42
• It would be nice to see how much general solution would you like to have because I'm afraid of wasting time giving you next suggestion which may not fit your needs. :) – Kuba Oct 29 '15 at 12:47
• Agreed, what is the general situation? Do you want any sublist within list to have its elements multiplied? The latter sounds interesting - you would have to selectively Apply – Jason B. Oct 29 '15 at 12:59

list = {x + 1, x - 3, {x - I, x + I}, {3, 3, 3}, a, b, {a, b, c, d}};

# /. List -> Times & /@ list

(*  {1 + x, -3 + x, (-I + x) (I + x), 27, a, b, a b c d}  *)


Try this:

list = {x + 1, x - 3, {x - i, x + i}} /. {x_, y_} -> x*y // Expand

(*  {1 + x, -3 + x, -i^2 + x^2} *)


Have fun!

• That method's not robust: it will fail, on something like {x + 1, {x - i, x + i}}. – murray Oct 29 '15 at 14:52
• @murray Right, unless we know that the OP lists are always more then consisting of two sublists (like in your counterexample). In that case the way I propose is most economical one. – Alexei Boulbitch Oct 29 '15 at 15:48
• @murray. Could always be made more robust with conditions on x and y; something like /. {x_ /; Head@x =!= List, y_ /; Head@y =!= List} -> x*y. – march Oct 29 '15 at 16:06
• @march Right, thank you, I did not think about it. – Alexei Boulbitch Oct 30 '15 at 8:13

This will only replace the Head with Times for lists, nothing else,

list2times = If[SameQ[Head[#], List], Times @@ #, #] &

list = {x + 1, x - 3, {x - I, x + I}, {3, 3, 3}, a,
b, {a, b, c, d}};
list2times /@ list
(* {1 + x, -3 + x, (-I + x) (I + x), 27, a, b, a b c d} *)