10
$\begingroup$

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.

$\endgroup$
10
$\begingroup$

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

$\endgroup$
7
$\begingroup$

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}]
$\endgroup$
7
$\begingroup$

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
]
$\endgroup$
  • 1
    $\begingroup$ Naughty naughty... a gem for the infixionado.Strong stuff ;-) $\endgroup$ – Yves Klett Apr 27 '12 at 17:56
  • 3
    $\begingroup$ 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. $\endgroup$ – rcollyer Apr 27 '12 at 18:21
6
$\begingroup$

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]
$\endgroup$
6
$\begingroup$

This is how I would do it:

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

$\endgroup$
5
$\begingroup$

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]
$\endgroup$
4
$\begingroup$

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}} *)
$\endgroup$
3
$\begingroup$
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}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy