-2
$\begingroup$
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]
$\endgroup$
  • 3
    $\begingroup$ Look up MapAt[]; combine with Apply[]. $\endgroup$ – J. M. will be back soon Oct 29 '15 at 12:35
  • $\begingroup$ 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. $\endgroup$ – GambitSquared Oct 29 '15 at 12:41
  • $\begingroup$ ...then you might want to use Position[] also. $\endgroup$ – J. M. will be back soon Oct 29 '15 at 12:42
  • 1
    $\begingroup$ 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. :) $\endgroup$ – Kuba Oct 29 '15 at 12:47
  • 1
    $\begingroup$ 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 $\endgroup$ – Jason B. Oct 29 '15 at 12:59
2
$\begingroup$
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}  *)
$\endgroup$
2
$\begingroup$

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!

$\endgroup$
  • $\begingroup$ That method's not robust: it will fail, on something like {x + 1, {x - i, x + i}}. $\endgroup$ – murray Oct 29 '15 at 14:52
  • $\begingroup$ @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. $\endgroup$ – Alexei Boulbitch Oct 29 '15 at 15:48
  • $\begingroup$ @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. $\endgroup$ – march Oct 29 '15 at 16:06
  • $\begingroup$ @march Right, thank you, I did not think about it. $\endgroup$ – Alexei Boulbitch Oct 30 '15 at 8:13
1
$\begingroup$

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} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.