List - rotate

Alex Martelli aleax at
Wed Jan 23 08:48:53 EST 2002

"Nikolai Kirsebom" <nikolai.kirsebom at> wrote in message
news:3c4e7b1a.1031701568 at
> Probably easy - but can't seem to find "the solution" to rotating
> content of a list (in one statement - competition with a lisp-guru !).
> For a string I do the following to Rotate Right:
> s = "abc"
> s[1:]+s[0]
> >> s = "bca"
> which works correctly.

s[1:]+s[0:1] yields a "rotated copy" for ANY sequence s, be it
a string, a list, a tuple, whatever.  But you need to
assign it to something, else it will go away as soon
as you're done with it.  It does NOT modify s in-place
in any case (strings and tuples are mutable, lists are
mutable but no mutation is performed in this case).

In the case of strings you don't need s[0:1] (you can
use just s[0]) because of one weird property: a single
character is also a "sequence"... specifically a string.
That doesn't work for other sequences:-).

> Tried the following for list, does not seem to work.
> a = [1,2,3]
> a[1:].append(a[0])

a[1:] is a COPY of the 'tail' of a.  You are not assigning
this copy to anything, so it goes away when you're done with
it.  Method append returns None.

If you just want to rebind NAME a, without altering
the list OBJECT it was first bound to:

    a = a[1:]+a[0:1]

is fine.  If you want to modify in-place (not for a
string or tuple, of course, but OK for a list):

    a[:] = a[1:]+a[0:1]

If you want to use modifying-methods rather than
slicing and assignment,


should also be OK.


More information about the Python-list mailing list