[Tutor] rotating a list
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Sat Sep 20 21:22:11 EDT 2003
> PS. If my man Danny is out there... 'Hi'
Hey Kevin, it's been a long time!
Looks like you've gotten a few responses to the list-rotation question, so
I'd better not regurgitate them too much. *grin*
But just out of curiosity, is it necessary that we do have to account for
rotating the list of length one or zero?
If so, Gregor's solution:
###
def rotate(x):
x[:-1],x[-1] = x[1:],x[0]
###
will need an amendment to make it work on empty lists, or else we may run
into an IndexError:
###
>>> L = []
>>> rotate(L)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in rotate
IndexError: list index out of range
###
One way we can fix the definition is to redefine it so that it always does
list slicing on its input:
###
>>> 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*
Talk to you later!
More information about the Tutor
mailing list