10
$\begingroup$

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

$\endgroup$
  • 4
    $\begingroup$ Aaand everyone posted basically the same answer ;) $\endgroup$ – corey979 May 4 '18 at 20:13
4
$\begingroup$
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}}

$\endgroup$
  • $\begingroup$ PadRight[#, 3, "Fixed"] & /@ {{1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}} fails $\endgroup$ – corey979 May 4 '18 at 20:08
  • $\begingroup$ thank you @corey979. changed 3 to Max@Length@list $\endgroup$ – kglr May 4 '18 at 20:09
  • $\begingroup$ very elegant, cheers $\endgroup$ – jarhead May 4 '18 at 20:10
12
$\begingroup$
With[{n = Max[Length /@ list]}, PadRight[#, n, Last @ #] & /@ list]
$\endgroup$
  • 1
    $\begingroup$ Unlike the other answers, this version avoids needlessly computing Max[Length /@ list] over and over again. $\endgroup$ – Carl Woll May 4 '18 at 20:19
8
$\begingroup$
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].

$\endgroup$
  • $\begingroup$ Best answer, IMHO. I just knew there was this kind of elegant approach. $\endgroup$ – LLlAMnYP May 7 '18 at 9:55
4
$\begingroup$
Clear[pad]
pad = Function[list,
   PadRight[#, Max[Length /@ list], Last@#] & /@ list
   ];
pad@{{1}, {1}, {1}, {1, 6}, {1, 4}, {1, 3, 5}, {1, 3, 2}}
$\endgroup$
3
$\begingroup$
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.

$\endgroup$
  • $\begingroup$ I think it needs some adjustments $\endgroup$ – MarcoB May 4 '18 at 20:18
  • $\begingroup$ @MarcoB thanks, fixed. I was hoping to avoid repeated evaluation of Length/@list, but the evaluation sequence foiled me. $\endgroup$ – LLlAMnYP May 7 '18 at 9:54
2
$\begingroup$

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

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.