Python list rotation

Possible duplicate:
Efficient way to move a list in python

I would like to rotate the Python list with an arbitrary number of elements left or right (the latter with a negative argument).

Something like that:

>>> 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 can I do that?

+58
python list rotation
Feb 26 2018-12-12T00:
source share
4 answers
 def rotate(l, n): return l[-n:] + l[:-n] 

More traditional 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] 

Arguments rotate is a list and an integer denoting a shift. The function creates two new lists using slicing and returns the union of these lists. The rotate function does not change the input list.

+109
Feb 26 '12 at 22:30
source share

If applicable, you can 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 expect it to be faster than the built-in list.

+80
Feb 26 2018-12-12T00:
source share

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 x values, use:

 def rotate(li, x): return li[-x % len(li):] + li[:-x % len(li)] 
+12
Feb 26 2018-12-12T00:
source share
 >>> 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] 

General rotation of n 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 rotation direction to be the same as your example, just rotate y in rotation.

 def rotate(l, y=1): if len(l) == 0: return l y = -y % len(l) # flip rotation direction return l[y:] + l[:y] 
+4
Feb 26 2018-12-12T00:
source share



All Articles