Prepend 0 to sublists
lists = RandomInteger[{1, 9}, {4, 5}]
{{7, 4, 9, 9, 7}, {4, 2, 5, 5, 2}, {6, 5, 9, 2, 4}, {1, 9, 4, 7, 2}}
ArrayPad[lists, {0, {1, 0}}]
{{0, 7, 4, 9, 9, 7}, {0, 4, 2, 5, 5, 2}, {0, 6, 5, 9, 2, 4}, {0, 1, 9, 4, 7, 2}}
There are of course many ways to do this.
Since you are interested in learning here are some others, more or less practical:
Prepend[#, 0]& /@ lists
Prepend[0] /@ lists (* version 10 operator form *)
Join[{0} & /@ lists, lists, 2]
{0, ##} & @@@ lists
lists /. {x__Integer} :> {0, x}
PadLeft[#, Dimensions@# + {0, 1}] &@lists
Rojo expressed doubt about the speed of ArrayPad
. Here are some comparative timings using Packed Arrays, which one should use if speed is a concern:
lists = RandomInteger[99, {50000, 35}];
timeAvg =
Function[x,
Do[If[# > 1, Return[#/5^i]] & @@ Timing@Do[x, {5^i}], {i, 0, 15}],
HoldFirst];
Transpose@{ConstantArray[0, Length@#], Sequence @@ Transpose@#} &@lists // timeAvg
ArrayPad[lists, {0, {1, 0}}] // timeAvg
Join[0 ~ConstantArray~ {Length@#, 1}, #, 2] &@lists // timeAvg
ArrayFlatten@{{0, lists}} // timeAvg
0.00604
0.0019968
0.001224
0.0010032
ArrayFlatten
is the fastest, taking 82% as long as Join
/ConstantArray
and 50% as long as ArrayPad
.
Now an unpackable array (strings):
lists = RandomChoice["a" ~CharacterRange~ "z", {50000, 35}];
Transpose@{ConstantArray[0, Length@#], Sequence @@ Transpose@#} &@
lists // timeAvg
ArrayPad[lists, {0, {1, 0}}] // timeAvg
Join[0 ~ConstantArray~ {Length@#, 1}, #, 2] &@lists // timeAvg
ArrayFlatten@{{0, lists}} // timeAvg
0.023464
0.024088
0.024088
0.08236
Here ArrayFlatten
takes 342% and 351% as long as the other methods, which are all about the same.
Conclusion: use ArrayFlatten
when you're sure the data is a packed array of the same type as the value you are inserting; use Join
or ArrayPad
when you are not.
list = {{1, 2}, {3, 4}, {5, 6}};
Flatten /@ Tuples[{{0}, list}]
{{0, 1, 2}, {0, 3, 4}, {0, 5, 6}}
Join @@@ Tuples[{{{0}}, list}]
the latter method (thanks to kguler) is even faster than the former one.
These toys haven't been mentioned yet :
Join[ {0}, #] & /@ list
Flatten /@ ({0, #} & /@ list)
MapThread[ Join, {ConstantArray[{0}, Length @ list], list}]
Thread[Join[{0}, Transpose@list]]
One convenient method, originally due to Janus (see here):
list = {{1, 2}, {3, 4}, {5, 6}};
ArrayFlatten@{{0, list}}
giving
(* {{0, 1, 2}, {0, 3, 4}, {0, 5, 6}} *)
See here for some interesting comparisons by Timo