Consider the following list:

list = {{1}, {1}, {1}, {1, 6}, {1, 4}, {1, 3, 5}, {1, 3, 2}};


How can the sub-lists be padded to the length of the longest sub-list (in this case 3), with the last value of the sub-list? The expected result is

{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 6, 6}, {1, 4, 4}, {1, 3, 5}, {1, 3, 2}}

• Aaand everyone posted basically the same answer ;) Commented May 4, 2018 at 20:13

PadRight[#, Max[Length /@ list], "Fixed"] & /@ list


{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 6, 6}, {1, 4, 4}, {1, 3, 5}, {1, 3, 2}}

• PadRight[#, 3, "Fixed"] & /@ {{1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}} fails Commented May 4, 2018 at 20:08
• thank you @corey979. changed 3 to Max@Length@list
– kglr
Commented May 4, 2018 at 20:09
• very elegant, cheers Commented May 4, 2018 at 20:10
With[{n = Max[Length /@ list]}, PadRight[#, n, Last @ #] & /@ list]

• Unlike the other answers, this version avoids needlessly computing Max[Length /@ list] over and over again. Commented May 4, 2018 at 20:19
PadRight[list, Automatic, list[[All, {-1}]]]


{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 6, 6}, {1, 4, 4}, {1, 3, 5}, {1, 3, 2}}

The 3rd argument can also be Take[list, All, -1].

• Best answer, IMHO. I just knew there was this kind of elegant approach. Commented May 7, 2018 at 9:55
Clear[pad]
PadRight[#, Max[Length /@ list], Last@#] & /@ list
];
pad@{{1}, {1}, {1}, {1, 6}, {1, 4}, {1, 3, 5}, {1, 3, 2}}

Map[Function[sl, PadRight[sl, Max[Length /@ list], Last@sl]], list]


As MarcoB rightly noted, the original version of the answer had a couple of missing brackets and did not correctly inject the arguments into Function which has HoldAll attribute. This answer is of course very similar to many others.

• I think it needs some adjustments Commented May 4, 2018 at 20:18
• @MarcoB thanks, fixed. I was hoping to avoid repeated evaluation of Length/@list, but the evaluation sequence foiled me. Commented May 7, 2018 at 9:54

Another possible way:

With[{size = Max@(Length /@ list)},
Join[#, ConstantArray[Last@#, size - Length@#]] & /@ list]


{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 6, 6}, {1, 4, 4}, {1, 3, 5}, {1, 3, 2}}

list = {{1}, {1}, {1}, {1, 6}, {1, 4}, {1, 3, 5}, {1, 3, 2}};


Using SequenceReplace (new in 11.3) and Splice (new in 12.1)

SequenceReplace[#, x : {a_, 0 ..} :> Splice[x /. 0 :> a]] & /@ PadRight[list]


{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 6, 6}, {1, 4, 4}, {1, 3, 5}, {1, 3, 2}}

l = {{1}, {1}, {1}, {1, 6}, {1, 4}, {1, 3, 5}, {1, 3, 2}};


Another way using Table and Insert:

s = Max@(Length /@ list);

With[{size = s}, Insert[#, Splice@Table[Last@#, size - Length@#], -1] & /@ l]


{{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 6, 6}, {1, 4, 4}, {1, 3, 5}, {1, 3, 2}}$$`$$