10

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.

kglr
  • 394,356
  • 18
  • 477
  • 896

8 Answers8

10

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

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
7

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}]
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
7

This is how I would do it:

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

mohit6up
  • 281
  • 1
  • 4
7

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
]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 1
    Naughty naughty... a gem for the infixionado.Strong stuff ;-) – Yves Klett Apr 27 '12 at 17:56
  • 3
    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
6

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]
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
5

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]
kglr
  • 394,356
  • 18
  • 477
  • 896
4

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}} *)
rm -rf
  • 88,781
  • 21
  • 293
  • 472
user1066
  • 17,923
  • 3
  • 31
  • 49
3
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}}*)
chyanog
  • 15,542
  • 3
  • 40
  • 78