>>> a = [1,2,3,4,5]
>>> a.append(a.pop(0))
>>> a
[2, 3, 4, 5, 1]
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.deque
if it is available in your version of Python, which allow objects to be inserted and removed from either end in approximately O(1) time:
>>> a = collections.deque([1,2,3,4,5])
>>> a
deque([1, 2, 3, 4, 5])
>>> a.rotate(-1)
>>> a
deque([2, 3, 4, 5, 1])
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:
>>> c = a
>>> # rotate a
With your method, c
would continue to refer to the original, unrotated list, and with my methods, it will refer to the updated, rotated list/deque.