# How to add zeros to uneven list

I'm reading a book on MMA and it has an example

Range @ Range @ 3 that produces {{1}, {1, 2}, {1, 2, 3}}

What if I want to make it as matrix 3 x 3, like so {{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}. This is perhaps very simple but most functions that I've learned so far operate on rectangular entities.

1. I think a didactical answer with relatively simple and often used functions would be something like:

ls = {{1}, {1, 2}, {1, 2, 3}};

n = 3;
Map[Join[#, Table[0, {n - Length[#]}]] &, ls]

Out[107]= {{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}


2. We can also see ls as the nonzero elements in a sparse matrix and program this:

In[103]:= Normal@SparseArray[Position[ls, _Integer] -> Flatten[ls]]

Out[103]= {{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}


3. And, of course, we can use the specialized function PadRight. (As mentioned by Kuba in a comment.)

• may be also ArrayReshape[#, {n}, 0] & /@ ls; and Table[0, n] seems easier than Table[0, {n}] May 5, 2017 at 19:37
• @garej Sure. But since the user is a beginner it is better to give instructive solutions than solutions that have to be deciphered. May 6, 2017 at 5:17

Some very complex answers. Not sure why you wouldn't simply use PadRight which was apparently referenced in a comment that is no longer there.

PadRight[{{1}, {1, 2}, {1, 2, 3}}]

(* {{1, 0, 0}, {1, 2, 0}, {1, 2, 3}} *)

• This is what I think after first glance. :)
– yode
May 6, 2017 at 6:24

In:

(*Method 1*)
Table[Range[3], 3] // LowerTriangularize
Array[#2 &, {3, 3}] // LowerTriangularize
Array[#1 &, {3, 3}] // Transpose // LowerTriangularize
BoxMatrix[1] Range[3] // Transpose // LowerTriangularize
BoxMatrix[1] + Range[0, 2] // Transpose // LowerTriangularize

(*Method 2*)
DiagonalMatrix[Range[#], # - 3] & /@ Range[3] // Plus @@ # &

(*Method 3*)
Table[FromDigits@Range[n] 10^(3 - n), {n, Range[3]}] // IntegerDigits

(*Method 4*)
10^Range[0, 2] // Map[# Quotient[FromDigits@Range[3], #] &] //
Reverse // IntegerDigits


Out:

{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}
{{1, 0, 0}, {1, 2, 0}, {1, 2, 3}}