Use collections.deque
You should use collections.deque
for this task and use the in-place method deque.rotate
designed specifically for this purpose.
Using a list
for this task would require expensive copying operations, while deque
is optimised for fast addition and removal of elements from the beginning and end of a queue. See TimeComplexity for more details.
from collections import deque
A = deque([1, 9, 7])
for i in range(len(A)):
print(A)
A.rotate()
deque([1, 9, 7])
deque([7, 1, 9])
deque([9, 7, 1])
Why your code does not work
The reason your code does not work is because you are modifying the same object rather than a copy. The following will work:
def rotation(N):
A = []
for i in range(len(N)):
N = N[:]
N.append(N.pop(0))
A.append(N)
return A
K = [1,9,7]
r = rotation(K)
print(r)
[[9, 7, 1], [7, 1, 9], [1, 9, 7]]
Further explanation
If you modify the same object, A
will consist of 3 lists with each list pointing to the same object and will therefore be guaranteed to be identical. Remember each list is just a bunch of pointers. If each pointer points to one object, changing it 3 times means the final assignment will be used for all the sublists.