Python list rotation [duplicate]
Solution 1:
def rotate(l, n):
return l[-n:] + l[:-n]
More conventional direction:
def rotate(l, n):
return l[n:] + l[:n]
Example:
example_list = [1, 2, 3, 4, 5]
rotate(example_list, 2)
# [3, 4, 5, 1, 2]
The arguments to rotate
are a list and an integer denoting the shift. The function creates two new lists using slicing and returns the concatenatenation of these lists. The rotate
function does not modify the input list.
Solution 2:
If applicable, you could use collections.deque
as a solution:
import collections
d = collections.deque([1,2,3,4,5])
d.rotate(3)
print d
>>> deque([3, 4, 5, 1, 2])
As a bonus, I'd expect it to be faster than in-built list.
Solution 3:
The following function will rotate the list l
, x
spaces to the right:
def rotate(l, x):
return l[-x:] + l[:-x]
Note that this will only return the original list if x
is outside the range [-len(l), len(l)]
. To make it work for all values of x
, use:
def rotate(li, x):
return li[-x % len(li):] + li[:-x % len(li)]