Rotating lists?

Robert Brewer fumanchu at amor.org
Thu Sep 16 00:26:07 CEST 2004


Ivan Voras wrote:
> I need to transform this:
> 
> [1,2,3]
> 
> into this:
> 
> [2,3,1]
> 
> (a left-rotation. Actually, any rotation will do).
> 
> I tried:
> 
> a = a[1:] + a[0]
> 
> which doesn't work because there's no __add__ between a list and 
> integer, and:
> 
> a = a[1:].append(a[0])
> 
> but it doesn't work, since append returns None :( Right now, 
> I'm doing 
> it with a temporary variable and it looks ugly - is there an 
> elegant way 
> of doing it?

Odd that you would use a slice for only half of it. Did you try:

>>> def rotleft(seq):
... 	return seq[1:] + seq[:1]
... 
>>> rotleft([1,2,3])
[2, 3, 1]

? There are issues with such a simple function (mostly how to deal with
corner cases), but that should be the piece you're missing.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list