Cycle around a sequence

Terry Reedy tjreedy at udel.edu
Wed Feb 8 02:41:01 CET 2012


On 2/7/2012 8:10 PM, Mark Lawrence wrote:
> I'm looking at a way of cycling around a sequence i.e. starting at some
> given location in the middle of a sequence and running to the end before
> coming back to the beginning and running to the start place. About the
> best I could come up with is the following, any better ideas for some
> definition of better?
>
> PythonWin 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit
> (Intel)] on win32.
> Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin'
> for further copyright information.
>  >>> from itertools import chain
>  >>> a=range(10)
>  >>> g = chain((a[i] for i in xrange(4, 10, 1)), (a[i] for i in xrange(4)))
>  >>> for x in g: print x,
> ...
> 4 5 6 7 8 9 0 1 2 3

a=range(10)
n = len(a)
off = 4
for k in (a[(i+off) % n] for i in range(n)):
   print(a[k], end = ' ')

-- 
Terry Jan Reedy




More information about the Python-list mailing list