tags:

views:

286

answers:

1

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 an build-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
+11  A: 
>>> 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.

Miles
a.append(a.pop(0)) is the solution i was looking for, since i will need this for a small list (<20 values) only. thanks
dkson