Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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 Answer

0 votes
by (106k points)

The efficient way to rotate a list in python is to use a collections.deque it is optimized for pulling and pushing on both ends. This method has 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()

Related questions

0 votes
4 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)

Browse Categories

...