114

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?

10
  • 3
    I don't use Python, but if you have a push/pop method, you can l.push(l.pop()). Then for loop it. That would cover moving forward.
    – Ryan Amos
    Feb 26, 2012 at 22:29
  • 1
    Thanks for the links to other questions. I tried searching Google and SO for python list rotation and didn't find any of those. This question may serve as a landing page for people thinking of 'rotating' rather than 'shifting'. Feb 26, 2012 at 22:32
  • 1
    @DrewNoakes: both show up in the first page of SO search results for "python list rotate". Need to use shorter forms of the words, I think. ;-)
    – DSM
    Feb 26, 2012 at 22:35
  • 3
    The other question is specifically about efficiency; this one may cover slightly different ground. Feb 26, 2012 at 22:38
  • 4
    This "duplicate", and the answers here were more useful than the original. Thanks!
    – mdandr
    May 4, 2016 at 17:13

4 Answers 4

207
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.

6
  • Nice and simple. It rotates the opposite direction to that specified in the question though. Feb 26, 2012 at 22:36
  • 1
    @S.Lott: One could argue that the OP's direction is backwards in his example. Most Python tutorials on slice idiom with a list rotation has the sign convention the same direction as Mr E first rotation function...
    – the wolf
    Feb 26, 2012 at 23:05
  • 12
    I'd add n = n % len(n) to make this work for n > len(n). Nov 23, 2013 at 20:31
  • 2
    Not sure what you mean. The function doesn't modify the input parameter, it returns a new list. Probably best to ask a new question about your issue.
    – YXD
    Mar 19, 2014 at 15:51
  • 13
    @user1071136 I think you mean n = n % len(l).
    – ktbiz
    May 3, 2016 at 20:07
129

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.

3
28

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)]
6
  • Is there a way to this without return ? I tried l=l[n:] + l[:n] but when I try to return a l I get the original.
    – GinKin
    Mar 18, 2014 at 17:46
  • @GinKin Why without a return? That's how you return things from a function. I mean, you could use a lambda, but that just makes the return implicit. Mar 18, 2014 at 17:54
  • I want to make it 'in place' so it won't return anything and if I'll type >>> l after running the function I'll get a the rotated list, not the original.
    – GinKin
    Mar 18, 2014 at 17:59
  • 2
    @GinKin Instead of return ... you can say l[:] = ... and it will do it in place. I don't recommend this, though. Mar 18, 2014 at 19:28
  • 1
    @GinKin Functions in Python are generally expected to be side-effect free; normally you would only change one of the parameters if it was the first (self) argument to a method. It's just a convention, though. Mar 19, 2014 at 18:19
8
>>> l=[1,2,3,4]
>>> l[1:]+l[:1]
[2, 3, 4, 1]
>>> l=[1,2,3,4]
>>> l[2:]+l[:2]
[3, 4, 1, 2]
>>> l[-1:]+l[:-1]
[4, 1, 2, 3]

A general rotate n to the left (positive y in the call to rotate) or right (negative y) then:

def rotate(l, y=1):
   if len(l) == 0:
      return l
   y = y % len(l)    # Why? this works for negative y

   return l[y:] + l[:y]

If you want the direction of rotation to be the same as your example, just negate y in rotate.

def rotate(l, y=1):
   if len(l) == 0:
      return l
   y = -y % len(l)     # flip rotation direction

   return l[y:] + l[:y]

Not the answer you're looking for? Browse other questions tagged or ask your own question.