# Moving every element of a list to the left one place (RotateLeft) but making last element 0

I have many lists that I would like to RotateLeft, but i want the last element to be 0 (rather than the initial first element).

My starting list is:

listA1 = {1, 2, 3}
listA2 = {2, 3, 4}
listB1 = {4, 5, 6}
listB2 = {3, 5, 7}
listC1 = {1, 2, 6}
listC2 = {5, 4, 3}
nestedList = {{listA1, listA2}, {listB1, listB2}, {listC1, listC2}}


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

And my desired output is:

{{{2, 3, 0}, {3, 4, 0}}, {{5, 6, 0}, {5, 7, 0}}, {{2, 6, 0}, {4, 3, 0}}}

Using RotateLeft, i get close to the result:

currentOutput = RotateLeft[nestedList, {0, 0, 1}]


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

But the last element in each list is the first element.

Is there a very simple way to either extend my current code or alternatively do it all in one simple step?

• You could use ReplacePart[]: ReplacePart[RotateLeft[{{{1, 2, 3}, {2, 3, 4}}, {{4, 5, 6}, {3, 5, 7}}, {{1, 2, 6}, {5, 4, 3}}}, {0, 0, 1}], {_, _, -1} -> 0] Nov 28, 2019 at 23:28

You can use ArrayPad to get the desired output in a single step:

ArrayPad[nestedList, {{0}, {0}, {-1, 1}}]


{{{2, 3, 0}, {3, 4, 0}}, {{5, 6, 0}, {5, 7, 0}}, {{2, 6, 0}, {4, 3, 0}}}

Alternatively, you can use PadRight:

PadRight[nestedList[[All, All, 2 ;;]], {Automatic, Automatic, 3}]


{{{2, 3, 0}, {3, 4, 0}}, {{5, 6, 0}, {5, 7, 0}}, {{2, 6, 0}, {4, 3, 0}}}

You can also Apply the function {##2, 0} & to nestedList at level 2:

Apply[{##2, 0} &, nestedList, {2}]


{{{2, 3, 0}, {3, 4, 0}}, {{5, 6, 0}, {5, 7, 0}}, {{2, 6, 0}, {4, 3, 0}}}

And for fun:

☺ = {##2, 0} & @@@ # & /@ # &;
☺ @ nestedList


{{{2, 3, 0}, {3, 4, 0}}, {{5, 6, 0}, {5, 7, 0}}, {{2, 6, 0}, {4, 3, 0}}}

I prefer @kglr solution but as an alternative you can do this as a second step:

currentOutput[[All, All, 3]] = 0

(list = {{{1, 2, 3}, {2, 3, 4}}, {{4, 5, 6}, {3, 5, 7}}, {{1, 2,
6}, {5, 4, 3}}}) // Map[MatrixForm]

(res = Map[Last@Partition[#, 3, 2, {2, -2}, 0] &, list, {-2}]) //
Map[MatrixForm]


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

Replace[list, {_, a_, b_} :> {a, b, 0}, {2}]


{{{2, 3, 0}, {3, 4, 0}}, {{5, 6, 0}, {5, 7, 0}}, {{2, 6, 0}, {4, 3, 0}}}

Map[Append[0], list[[;;, ;;, 2;;]], {2}]


{{{2, 3, 0}, {3, 4, 0}}, {{5, 6, 0}, {5, 7, 0}}, {{2, 6, 0}, {4, 3, 0}}}

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


Using Threaded:

Map[# + Threaded[{0, 0, -Last@#}] &@RotateLeft[#] &, list, {2}]

(*{{{2, 3, 0}, {3, 4, 0}}, {{5, 6, 0}, {5, 7, 0}}, {{2, 6, 0}, {4, 3, 0}}}*)