You can rotate the list in place in Python using deque :
>>> from collections import deque >>> d=deque([1,2,3,4,5]) >>> d deque([1, 2, 3, 4, 5]) >>> d.rotate(2) >>> d deque([4, 5, 1, 2, 3]) >>> d.rotate(-2) >>> d deque([1, 2, 3, 4, 5])
Or with lists of lists:
>>> li=[1,2,3,4,5] >>> li[2:]+li[:2] [3, 4, 5, 1, 2] >>> li[-2:]+li[:-2] [4, 5, 1, 2, 3]
Note that the sign convention is the opposite of deque.rotate vs slices.
If you want to use a function that has the same convention:
def rotate(l, y=1): if len(l) == 0: return l y = -y % len(l)
For numpy just use np.roll
>>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.roll(a, 1) array([9, 0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> np.roll(a, -1) array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
Or you can use the numpy version of the same rotate above (again, noting the difference in the vs np.roll sign):
def rotate(a,n=1): if len(a) == 0: return a n = -n % len(a)