14

Thread can do this

Thread[{a, {b, c, d}}]
{{a, b}, {a, c}, {a, d}}

But when above a, b, c and d are themselves Lists, for instance, used as a representation for 2D/3D points, it will not work as a naive generalization

Thread[{{a, b}, {{x, y}, {z, w}, {u, v}}}]

which just raises an error.

Here what is intended for is

{{{a, b}, {x, y}}, {{a, b}, {z, w}}, {{a, b}, {u, v}}}

So can it still be realized by Thread? If yes, how? If no, then do there exist any concise and efficient workarounds?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574

1 Answers1

18

A level specification can help (we have to specify the head to thread over, too):

Thread[{{a, b}, {{x, y}, {z, w}, {u, v}}}, List, {2}]

{{{a, b}, {x, y}}, {{a, b}, {z, w}}, {{a, b}, {u, v}}}

Note that this unpacks arrays, so I would not suggest that for big datasets. I that case, I would propose a ConstantArray/Transpose combo:

n = 1000000 ;
a = RandomReal[{-1, 1}, 2];
b = RandomReal[{-1, 1}, {n, 2}];

Thread[{a, b}, List, {2}] // Developer`PackedArrayQ // AbsoluteTiming

Transpose[{ConstantArray[a, n],b}] // Developer`PackedArrayQ // AbsoluteTiming

{0.347755, False}

{0.046035, True}

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309