Adding elements to a collection of lists

I would like to add element a at the start of a series of lists.

For example I have a collection of lists called

LISTS1 = {{1,2,3,4,5},{2,3,4,5,6},{3,4,5,6,7},{4,5,6,7,8}}


Now I want to add a 0 to the beginning of the first list, two 0s to the second list and so on, to get:

{{0,1,2,3,4,5},{0,0,2,3,4,5,6},{0,0,0,3,4,5,6,7},{0,0,0,0,4,5,6,7,8}}.


I suspect this needs to be done using the Prepend command in combination with something to change the numbers of elements to add for each individual list in the collection.

9 Answers

This would be a neat way to do it:

LISTS1 = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}, {4, 5, 6, 7, 8}};

MapIndexed[Join[Table[0, #2], #1] &, LISTS1]


{{0, 1, 2, 3, 4, 5}, {0, 0, 2, 3, 4, 5, 6}, {0, 0, 0, 3, 4, 5, 6, 7}, {0, 0, 0, 0, 4, 5, 6, 7, 8}}

One possibility without particular attention to performance:

Sample input:

data = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}, {4, 5, 6, 7, 8}}


Let's generate the zeros ...

zeros = ConstantArray[0, #] & /@ Range@Length[data]


... and prepend them to the sublists:

MapThread[Join, {zeros, data}]


This is how I would do it:

Table[Join[Table[0, {j, i}], LISTS1[[i]]], {i, Length[LISTS1]}]

A variation of Szabolcs's method with extra speed and infix! ;-)

list = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}, {4, 5, 6, 7, 8}};

Join[
0 ~ConstantArray~ # & ~Array~ Length@list,
list,
2
]

• Naughty naughty... a gem for the infixionado.Strong stuff ;-) Apr 27, 2012 at 17:56
• Horrible, horrible to read. However, it has the advantage that ConstantArray returns a packed array, and using the third argument of Join is always nice. Apr 27, 2012 at 18:21

A slight variation of Chris's answer:

LISTS1 = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}, {4, 5, 6, 7, 8}};

MapIndexed[ArrayPad[#1, {First[#2], 0}] &, LISTS1]


Two variations of MapThread and MapIndexed:

MapThread with PadLeft:

  MapThread[PadLeft[#1, #2 + Length@#1] &, {LISTS1,Range@Length[LISTS1]}]


MapIndexed with PadLeft:

   MapIndexed[PadLeft[#, #2 + Length@#1] &, LISTS1]


A slight variant:

Join[ ConstantArray[0, #], LISTS1[[#]]] & /@ Range@Length@LISTS1


giving

(* {{0, 1, 2, 3, 4, 5}, {0, 0, 2, 3, 4, 5, 6}, {0, 0, 0, 3, 4, 5, 6, 7},
{0, 0, 0, 0, 4, 5, 6, 7, 8}} *)

ls = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {3, 4, 5, 6, 7}, {4, 5, 6, 7, 8}};
Join[0 Range@Range@Length@ls, ls, 2]

(*{{0, 1, 2, 3, 4, 5}, {0, 0, 2, 3, 4, 5, 6}, {0, 0, 0, 3, 4, 5, 6, 7},
{0, 0, 0, 0, 4, 5, 6, 7, 8}}*)

list = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5, 6},
{3, 4, 5, 6, 7},
{4, 5, 6, 7, 8}};


Using ReplacePart

ReplacePart[list, i_ :> Flatten[{Table[0, i], list[[i]]}]]


{{0, 1, 2, 3, 4, 5},
{0, 0, 2, 3, 4, 5, 6},
{0, 0, 0, 3, 4, 5, 6, 7},
{0, 0, 0, 0, 4, 5, 6, 7, 8}}

ReplacePart[list, i_ :> PadLeft[list[[i]], i + Last @ Dimensions @ list]]


same result