3
$\begingroup$

I have two (fairly large) lists of equal length & would like to pair them up.

eg - from:

a = {{0, 1}, {0, 2}, {0, 3}};
b = {{1, 2}, {1, 3}, {1, 4}};

I would like to get:

{{{0, 1}, {1, 2}}, {{0, 2}, {1, 3}}, {{0, 3}, {1, 4}}}

I have looked at various thing like Tuple, but can't see a way of doing it efficiently.

$\endgroup$

3 Answers 3

5
$\begingroup$

Transpose is convenient for this:

Transpose[{a, b}]

(* Equivalently: *)
{a, b}\[Transpose]
(* {{{0, 1}, {1, 2}}, {{0, 2}, {1, 3}}, {{0, 3}, {1, 4}}} *)

You can make \[Transpose] with EsctrEsc

Or you can use MapThread:

MapThread[List, {a, b}]

Thread works too:

Thread[{a, b}]

So which one to use? They are all pretty fast, but Transpose is in my experience the fastest and if you happen to have l={a, b} as a packed array it will remain packed which is preferable.

$\endgroup$
3
  • $\begingroup$ @ ssch, Great! - Thank you - I can't get over the speed at which some of these questions are answered on this site! :) $\endgroup$
    – martin
    Nov 9, 2013 at 23:25
  • $\begingroup$ Incidentally, thanks also for the unintended help with (...) - little things like this help to clean up my code nicely :) $\endgroup$
    – martin
    Nov 9, 2013 at 23:28
  • $\begingroup$ @martin No problem :) $\endgroup$
    – ssch
    Nov 9, 2013 at 23:34
5
$\begingroup$

Another options not using Transpose is Flatten, just need to use {2} for second argument

Flatten[{a, b}, {2}]

But it looks like Transpose is still faster:

a = Table[{RandomReal[], RandomReal[]}, {5000000}];
b = Table[{RandomReal[], RandomReal[]}, {5000000}];
First@Timing[Flatten[{a, b}, {2}]]  (* 0.234002 *)
First@Timing[Transpose[{a, b}]]  (* 0.156001*)
$\endgroup$
2
  • $\begingroup$ I can't find the {2} type of specification in the documentation, is it equivalent to {{2}}? $\endgroup$
    – ssch
    Nov 10, 2013 at 0:46
  • $\begingroup$ @ssch good question, I can't find it either, I just assumed it will work since this is a common level specification used by many other similar commands. So, I would have to say yes, but I am no expert in Mathematica specs, may be someone would know. At least it does give same results for this example. i.e {2} or {{2}}. $\endgroup$
    – Nasser
    Nov 10, 2013 at 0:56
2
$\begingroup$
Partition[Riffle[a,b],2]

{{{0, 1}, {1, 2}}, {{0, 2}, {1, 3}}, {{0, 3}, {1, 4}}}

On my machine this approach (0.51 secs) is faster than Flatten (0.66 secs) but slower than Transpose (0.37 secs) for the 5 million Random datasets.

$\endgroup$

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.