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?

27 Answers
27

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *