Rotating lists?

Peter Hansen peter at engcorp.com
Wed Sep 15 18:53:00 EDT 2004


Ivan Voras wrote:

> I need to transform this:
> [1,2,3]
> into this:
> [2,3,1]
> 
> Right now, I'm doing 
> it with a temporary variable and it looks ugly - is there an elegant way 
> of doing it?

 >>> l = range(1, 4)
 >>> l
[1, 2, 3]
 >>> import itertools
 >>> list(itertools.islice(itertools.cycle(l), 1, len(l)+1))
[2, 3, 1]

That is, build an iterator that cycles over l indefinitely,
then take a slice of it starting x items in (where x==1 in
this case) and continuing until you've retrieved a number
of elements equal to the length of the original sequence.

-Peter



More information about the Python-list mailing list