List - rotate

Mats Wichmann mats at
Fri Jan 25 21:26:55 CET 2002

On Wed, 23 Jan 2002 14:48:53 +0100, "Alex Martelli" <aleax at>

:"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).

This sounds like a problem from my Python class.  The challenge is to,
in stages, build a function that rotates a list any amount, either
left or right. Structured so that "success" for the problem can be
achieved without twigging that the same technique works for one hop or
many, works to go the other direction with just a negative count, and
even works for strings and tuples.  It's practice in writing a
function, not in thinking of "clever" solutions. Nonetheless, a goodly
number of students end up deciding they want to solve it something
like this:

def rot(seq, n=1):
	n = n % len(seq)
	return seq[n:] + seq[:n]

Mats Wichmann

More information about the Python-list mailing list