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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With