Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list rotation [duplicate]

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?

like image 316
Drew Noakes Avatar asked Feb 26 '12 22:02

Drew Noakes


1 Answers

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.

like image 156
YXD Avatar answered Sep 21 '22 23:09

YXD