# Maybe a stupid idea

Jeff Epler jepler at unpythonic.net
Wed Dec 31 20:18:55 CET 2003

On Wed, Dec 31, 2003 at 06:45:05PM +0000, Kirk Strauser wrote:
> >>> def cycle(a,b):
> ...     return range(a,b)+range(b,a,-1)
> ...
> >>> cycle(0,10)
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

You might also define cycle as an iterator
>>> def cycle(a, b):
...     return itertools.chain(xrange(a, b), xrange(b, a, -1))
>>> list(cycle(0, 10)

Furthermore, you might want to treat the one-argument version similarly
to range:
>>> def cycle(a, b=None):
...     if b is None: a, b = 0, a
...     return itertools.chain(xrange(a, b), xrange(b, a, -1))
>>> list(cycle(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

You could also change it to support a step argument:
>>> def cycle(a, b=None, c=1):
...     if b is None: a, b = 0, a
...     return itertools.chain(xrange(a, b, c), xrange(b, a, -c))
>>> list(cycle(5, 10, 2))
[5, 7, 9, 10, 8, 6]
... though that last result looks a bit odd.  This must be the problem
with hypergeneralization I hear so much about.

Jeff