# Efficient way to rotate a list in python

### Question

What is the most efficient way to rotate a list in python? Right now I have something like this:

``````>>> def rotate(l, n):
...     return l[n:] + l[:n]
...
>>> l = [1,2,3,4]
>>> rotate(l,1)
[2, 3, 4, 1]
>>> rotate(l,2)
[3, 4, 1, 2]
>>> rotate(l,0)
[1, 2, 3, 4]
>>> rotate(l,-1)
[4, 1, 2, 3]
``````

Is there a better way?

1
240
8/3/2019 6:08:05 PM

### Accepted Answer

A `collections.deque` is optimized for pulling and pushing on both ends. They even have a dedicated `rotate()` method.

``````from collections import deque
items = deque([1, 2])
items.append(3)        # deque == [1, 2, 3]
items.rotate(1)        # The deque is now: [3, 1, 2]
items.rotate(-1)       # Returns deque to original state: [1, 2, 3]
item = items.popleft() # deque == [2, 3]
``````
250
11/8/2018 7:27:06 PM

What about just using `pop(0)`?

`list.pop([i])`

Remove the item at the given position in the list, and return it. If no index is specified, `a.pop()` removes and returns the last item in the list. (The square brackets around the `i` in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon