How to add zeros to uneven list
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}} *)
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}}
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.)