[Tutor] rotating a list

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Sep 21 13:17:35 EDT 2003


> >>>>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*
> >
> >
> >
> Me too! Thanks for the idea! (Of course we should replace L by x (or
> vice versa) ;-) ).

Uh, yeah.

Doh!  Serves me right for trying to in-place edit the text after I cut and
pasted it to my email.  I sometimes do that to make my variable names make
more sense, but this time, it really bit me badly.  Thanks for correcting
me.



>  >>> def rotate(x, n=1):
>         x[:-n], x[-n:] = x[n:], x[:n]
>
> This works also for n > len(x), but not correctly. Sometimes this will
> be needed to have some sort of continued rotation:
>
>  >>> def rotate(x, n=1):
>         n %= len(x)
>         x[:-n], x[-n:] = x[n:], x[:n]
>
>  >>> rotate(l,11)
>  >>> l
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>  >>>
>  >>> rotate(l,-2)
>  >>> l
> [9, 0, 1, 2, 3, 4, 5, 6, 7, 8]


Wow, that looks great!  I didn't even think about using modulo arithmetic
to handle negative rotations.


Thanks again!




More information about the Tutor mailing list