As with many things in Mathematica there are a great many ways to perform such a simple operation. Which one you choose can depend on what you are comfortable with and what performance level you require. I shall list several that come to mind. Some options have already been provided in other answer; I shall include them here for completeness.
A small data sample to keep things clean:
a = {{{1}, {2}, {3}}, {{4}, {5}, {6}}};
All lines return the same output; I shall include it only once:
a /. {x_} :> {x, 0}
Replace[a, {x_} :> {x, 0}, {2}]
Apply[{#, 0} &, a, {2}]
Join[a, 0*l1, 3]
ArrayPad[a, {0, 0, {0, 1}}]
a.{{1, 0}}
{{{1, 0}, {2, 0}, {3, 0}}, {{4, 0}, {5, 0}, {6, 0}}}
A special note regarding the last method (Dot
): the "zero" will inherit the type of the data, meaning that if a
is an array of Reals (as produced by N
) so too will be the zeros:
N[a].{{1, 0}}
{{{1., 0.}, {2., 0.}, {3., 0.}}, {{4., 0.}, {5., 0.}, {6., 0.}}}
This is also true of the Join
method, though by adding Chop
that could be changed.
Now a large (packed) data sample for performance timings:
a = RandomReal[{-9, 9}, {500000, 3, 1}];
A timing function:
SetAttributes[timeAvg, HoldFirst]
timeAvg[func_] := Do[If[# > 0.3, Return[#/5^i]] & @@ Timing @ Do[func, {5^i}], {i, 0, 15}]
Timings:
a /. {x_} :> {x, 0} // timeAvg
Replace[a, {x_} :> {x, 0}, {2}] // timeAvg
Apply[{#, 0} &, a, {2}] // timeAvg
Join[a, 0*a, 3] // timeAvg
ArrayPad[a, {0, 0, {0, 1}}] // timeAvg
a.{{1, 0}} // timeAvg
0.453
0.405
0.515
0.453
0.259
0.03372
(Timings all performed in version 7.)
Keeping packed arrays packed
As you can see the Dot
method is an order of magnitude faster than the rest. This largely due to the fact that the types are matched allowing the array to remain packed (because Dot
is able to handle arrays without unpacking).
By modifying the ArrayPad
method to also return a packed array (matching types, by specifying a machine precision zero for the padding element) we can get even greater speed:
ArrayPad[a, {0, 0, {0, 1}}, 0`] // timeAvg
0.01808
Likewise Alexey's Join
method can be made faster (in version 7) by matching types:
Join[a, 0` a, 3] // timeAvg
0.02744
(Version 7 behaves differently in that 0 * 1.1
returns 0
, whereas later versions return 0.
. An explicit imprecise zero is needed to return an array of Reals.)
This improvement cannot be applied to the Replace
, ReplaceAll
and Apply
methods because these functions are not (generally) capable of preserving packed arrays.
l1 /. {x_} -> {x, 0}
$\endgroup$Transpose[{Flatten[l1], Table[0, {Length[l1]}]}]
. But it seems that your real problem is structurally different from the simplified version you gave. Please give an excerpt of your real data. $\endgroup$extendList[l1_]
and then map that function on your big list. $\endgroup$