Rotating lists?
Jim Sizelove
sizelji at insightbb.com
Thu Sep 16 09:19:53 EDT 2004
Thorsten Kampe wrote:
>
> def rotate(seq,
> offset):
> """ shift seq to the left by offset, with the elements shifted off the
> beginning inserted back at the end """
> return seq[offset:] + seq[:offset]
You can also use a generator function:
def rotator(seq, offset=1):
while True:
yield seq
seq = seq[offset:] + seq[:offset]
T = rotator(range(5))
T.next()
[0, 1, 2, 3, 4]
T.next()
[1, 2, 3, 4, 0]
T.next()
[2, 3, 4, 0, 1]
You can rotate to the right using a negative offset:
L = rotator( range(5), -1 )
L.next()
[0, 1, 2, 3, 4]
L.next()
[4, 0, 1, 2, 3]
L.next()
[3, 4, 0, 1, 2]
More information about the Python-list
mailing list