[Tutor] cyclically rotate a list.

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 14 Feb 2002 08:46:18 +0100


On  0, kevin parks <kp87@lycos.com> wrote:
> How does one cyclically rotate a list (of arbitary size)
> so that given a list x= [0, 1, 2, 3, 4, 5, 6] one could say:
> rotate(x, y=0) -->[0, 1, 2, 3, 4, 5, 6]
> rotate(x, y=1) -->[1, 2, 3, 4, 5, 6, 0]
> 
> yeilding list like so (with y going modulo the list size 
> i suppose):
> 
> [0, 1, 2, 3, 4, 5, 6]
> [1, 2, 3, 4, 5, 6, 0]
> [2, 3, 4, 5, 6, 0, 1]
> [3, 4, 5, 6, 0, 1, 2]
> .
> .
> .
> [6, 0, 1, 2, 3, 4, 5]
> [0, 1, 2, 3, 4, 5, 6]
> 
> 
> I am hurting my brain on this one.

def rotate(x, y=1):
   if len(x) == 0:
      return x
   y = y % len(x) # Normalize y, using modulo - even works for negative y
   
   return x[y:] + x[:y]
   
Ever wondered why Python list indexing starts at 0, and why slices like
l[x:y] include the start point but not the end point? It's because
operations like this work out so neatly :-)

-- 
Remco Gerlich