8
$\begingroup$

I have a lists, list, and want shift it right by a given number of elements, m, extending the list by repeating the last element. A form that works is

Drop[#, m]& @ PadRight[#, Length[#] + m, Last[#]]& @ list

which, for

m = 3
list = {3, 0, 7, 2, 1}

gives

{2, 1, 1, 1, 1}

and for

m = 2
list = {3, 8, 2, 7, 1, 6}

gives

{2, 7, 1, 6, 6, 6}

This is what I want, but I wonder if there is a more idiomatic way to accomplish it.

$\endgroup$
  • $\begingroup$ Perhaps the accepted terminology is different among Mathematica users, but don't you mean you're shifting the list to the left? $\endgroup$ – David Zhang Jul 6 '15 at 20:46
  • $\begingroup$ @DavidZhang: Yes, indeed! $\endgroup$ – orome Jul 6 '15 at 20:47
7
$\begingroup$

I may be back to using gedanken Mathematica, but I'm confident this works:

m = 2;
ArrayPad[{3, 8, 2, 7, 1, 6}, {-m, m}, "Fixed"]
   {2, 7, 1, 6, 6, 6}
$\endgroup$
  • $\begingroup$ Cool. I knew there had to be something. $\endgroup$ – orome Jul 6 '15 at 13:35
4
$\begingroup$

ArrayPad does precisely what you want, nevertheless I'd suggest one more solution without calling a special function, which I think a little clearer than the original with Drop and PadRight:

Join[list[[m + 1 ;;]], Table[list[[-1]], {m}]]
$\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.