+3 votes
in Programming Languages by (12.7k points)
I want to rotate the elements of a list to the left or right. Is there any python function for this operation?

E.g.

[10, 20, 30, 40, 50, 60]

to

[60, 10, 20, 30, 40, 50]  or [20, 30, 40, 50, 60, 10]

1 Answer

+1 vote
by (27.1k points)

You can use the rotate(n) function of collections.deque class. If n is positive, it rotates the deque n steps to the right. If n is negative, rotate to the left.

First, you need to convert the list to deque using the deque() function.

Here is an example:

Rotate to the right

>>> from collections import deque
>>> a=[10,20,30,40,50,60]
>>> b=deque(a)
>>> b
deque([10, 20, 30, 40, 50, 60])
>>> b.rotate(1)
>>> list(b)
[60, 10, 20, 30, 40, 50]

Rotate to the left

>>> b=deque(a)
>>> b.rotate(-1)
>>> list(b)
[20, 30, 40, 50, 60, 10]


...