[Tutor] rotating a list
Charlie Clark
charlie at begeistert.org
Sun Sep 21 14:43:52 EDT 2003
On 2003-09-21 at 10:36:43 [+0200], tutor-request at python.org wrote:
> ###
> >>> def rotate(L):
> ... """Mutates list L and rotates all the elements to the left."""
> ... x[:-1], x[-1:] = x[1:], x[:1]
> ...
> ###
>
> The symmetry in the definition here appeals to me. *grin*
As usual Danny's solution is elegant an conclusive but his catch-all for
empty lists is maybe a bit too much. I actually found all of the solutions
too mathematic and not expressive enuff so came up with the following:
>>> l = [1, 2, 3]
>>> l.append(l.pop(0))
This will give IndexError for empty lists but with a helpful error message
telling you the list is empty. You can also rotate at different positions
using different values of pop() and you're using real list methods so it's
nice OO, I think.
Charlie
More information about the Tutor
mailing list