Possible Duplicate:
Efficient way to shift a list in python
I'd like to rotate a Python list by an arbitrary number of items to the right or left (the latter using a negative argument).
Something like this:
>>> l = [1,2,3,4]
>>> l.rotate(0)
[1,2,3,4]
>>> l.rotate(1)
[4,1,2,3]
>>> l.rotate(-1)
[2,3,4,1]
>>> l.rotate(4)
[1,2,3,4]
How might this be done?
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.