# Changing the order of elements in a list

I have a list of the form list1 = {1, 3, 4, 2, 5, 6} and I would like to replace each of the elements in the position of represented by the previous number in the list, for instance replace 1 in position 6, 3 in position 1, 4 in position 3, 2 in position 4 and so on. In the end I should get a list of the form {3, 5, 4, 2, 6, 1}. I am trying to do the following:

A = ConstantArray[0, Length[list1]]
NewList =
Table[
ReplacePart[
A,
(If[Position[list1, i] - 1 != 0,
Position[list1, i] - 1,
Position[List1, Last[List1]]) -> i],
{i, Range[Length[List1]]}]


I am using If inside ReplacePart to consider the case when an element is in position 1 and send it to the position of the last element of the permutation. However, this methos is not working. Could anyone tell me why? Is there is a more efficient method to solve this problem?

• The If expression in your code seems to be missing a ] at its end. – m_goldberg Jun 19 '16 at 14:13

newList = list1 = {1, 3, 4, 2, 5, 6};
newList[[RotateRight[list1]]] = list1;
newList


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

• Thanks! This solves my problem completely, but would you mind explaining the second line of the code? I don't really see what it is doing. – user41116 Jun 19 '16 at 15:47
• @user41116 The second line exposes a very useful purpose of Part by being able to Set arbitrary parts of a list at one time. By rotating the list right, you get {6, 1, 3, 4, 2, 5} and are essentially setting newlist[[6]] = 1, newlist[[1]] = 3 etc... – kale Jun 19 '16 at 17:58

Ordering[] is another opportunity:

list1 = {1, 3, 4, 2, 5, 6};
newList = list1[[Ordering[RotateRight[list1]]]]
(*{3, 5, 4, 2, 6, 1}*)

• Could you explain whi the expression list1[[Ordering[RotateRight[list1]]]] actually changes list1? I don't see how it is working. THanks! – user41116 Jun 19 '16 at 19:48