Efficient way to rotate a list in python

603    Asked by arun_3288 in Python , Asked on Apr 14, 2021

 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?

Answered by Arun Singh

The efficient way to rotate a list in python is to use a collections.deque it is used for pulling and pushing on both ends. This method includes another method called rotate() method.

from collections import deque

items = deque([1, 2])
items.append(3)
items.rotate(1)
items.rotate(-1)
item = items.popleft()

Your Answer

Interviews

Parent Categories