What is the most efficient way to rotate a list in python? Right now I have something like this:
>>> def rotate(l, n):
... return l[n:] + l[:n]
For a list X = ['a', 'b', 'c', 'd', 'e', 'f']
and a desired shift value of shift
less than list length, we can define the function list_shift()
as below
def list_shift(my_list, shift):
assert shift < len(my_list)
return my_list[shift:] + my_list[:shift]
Examples,
list_shift(X,1)
returns ['b', 'c', 'd', 'e', 'f', 'a']
list_shift(X,3)
returns ['d', 'e', 'f', 'a', 'b', 'c']