Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

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.

share|improve this answer
    
@ ssch, Great! - Thank you - I can't get over the speed at which some of these questions are answered on this site! :) –  martin Nov 9 '13 at 23:25
    
Incidentally, thanks also for the unintended help with (...) - little things like this help to clean up my code nicely :) –  martin Nov 9 '13 at 23:28
    
@martin No problem :) –  ssch Nov 9 '13 at 23:34
add comment

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*)
share|improve this answer
    
I can't find the {2} type of specification in the documentation, is it equivalent to {{2}}? –  ssch Nov 10 '13 at 0:46
    
@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}}. –  Nasser Nov 10 '13 at 0:56
add comment
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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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