1
$\begingroup$

Being a newcomer to Mathematica, I have the following question.

Given

x = Range@9~Partition~3;

and

y = {a, b, c};

I want to combine x and y so that

result = {{a, 1, 2, 3}, {b, 4, 5, 6}, {c, 7, 8, 9}};

I have written

MapPrepend[a_, b_] := Prepend[a[[#]], b[[#]]] & /@ Range@Length@b

which does the job, but I wonder if there are other, more functional solutions?

Probably this question has already been answered. In this case it would be very nice if you just would direct me to the links.

$\endgroup$
4
  • $\begingroup$ Join[{y}, Transpose[x]] // Transpose? $\endgroup$
    – kglr
    Commented May 14, 2014 at 18:58
  • $\begingroup$ Please take a look here, there is something for everyone: mathematica.stackexchange.com/questions/3069/… $\endgroup$
    – Yves Klett
    Commented May 14, 2014 at 18:59
  • $\begingroup$ @kguler - thanks, short and elegant (sometimes you don't see the wood for the trees). Should also be faster on large lists;) $\endgroup$
    – eldo
    Commented May 14, 2014 at 19:10
  • 2
    $\begingroup$ MapThread[Prepend, {x, y}] $\endgroup$
    – Kuba
    Commented May 14, 2014 at 21:45

2 Answers 2

2
$\begingroup$

I would simply do Flatten /@ Transpose[{y, x}].

$\endgroup$
1
  • $\begingroup$ also very nice, thank you. To not forget it I just added to my init.m a "MapFlatten". $\endgroup$
    – eldo
    Commented May 14, 2014 at 19:29
3
$\begingroup$

Unfortunately, in terms of speed there is probably not much to gain here. However, I guess this is fancy

Join[List /@ y, x, 2]
$\endgroup$
4
  • $\begingroup$ The shortest characterwise. Didn't know that "Join" accepts a level parameter. $\endgroup$
    – eldo
    Commented May 14, 2014 at 19:36
  • 1
    $\begingroup$ @eldo copy this: {y, ## & @@ x}\[Transpose] $\endgroup$
    – Kuba
    Commented May 14, 2014 at 21:01
  • 1
    $\begingroup$ @Kuba I can't beat that :). My shortest: {y, x /. _@z__ -> z}\[Transpose] $\endgroup$ Commented May 14, 2014 at 21:34
  • $\begingroup$ @JacobAkkerboom nice syntax :) it's interesting to see others habits :) $\endgroup$
    – Kuba
    Commented May 14, 2014 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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