I have a list
a=[1,2,3,4,5]
and want to ‘move’ its values so it changes into
a=[2,3,4,5,1]
and the next step
a=[3,4,5,1,2]
Is there a built-in function in Python to do that?
Or is there a shorter or nicer way than
b=[a[-1]]; b.extend(a[:-1]); a=b
This is expensive, though, as it has to shift the contents of the entire list, which is O(n). A better choice may be to use
collections.dequeif it is available in your version of Python, which allow objects to be inserted and removed from either end in approximately O(1) time:Note also that both these solutions involve changing the original sequence object, whereas yours creates a new list and assigns it to
a. So if we did:With your method,
cwould continue to refer to the original, unrotated list, and with my methods, it will refer to the updated, rotated list/deque.