# 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.

-

## migrated from stackoverflow.comApr 27 '12 at 15:03

This question came from our site for professional and enthusiast programmers.

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}]

-

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 ;-) – Yves Klett Apr 27 '12 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. – rcollyer Apr 27 '12 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]

-

This is how I would do it:

Table[Join[Table[0, {j, i}], LISTS1[[i]]], {i, Length[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}}*)

-