Cycle around a sequence

Christoph Hansen ch at radamanthys.de
Tue Feb 7 21:01:37 EST 2012


Mark Lawrence schrieb:
> 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?

# quick&dirty

seq=range(10)
for x in seq[4:]+seq[:4]:
     print x

# or

def oneround(seq, start=0):
     i=start
     l=len(seq)
     while True:
         yield seq[i]
         i = (i+1) % l
         if i==start: break

for x in oneround(range(50), 4):
     print x








More information about the Python-list mailing list