Efficient way to rotate a list in python Efficient way to rotate a list in python python python

Efficient way to rotate a list in python


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

from collections import dequeitems = 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]


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.)


Numpy can do this using the roll command:

>>> import numpy>>> a=numpy.arange(1,10) #Generate some data>>> numpy.roll(a,1)array([9, 1, 2, 3, 4, 5, 6, 7, 8])>>> numpy.roll(a,-1)array([2, 3, 4, 5, 6, 7, 8, 9, 1])>>> numpy.roll(a,5)array([5, 6, 7, 8, 9, 1, 2, 3, 4])>>> numpy.roll(a,9)array([1, 2, 3, 4, 5, 6, 7, 8, 9])