# qrange( [start,] stop[, step] ) is a generator, works similar to xrange()
def qrange(start, stop=None, step=1):
    """if start is missing it defaults to zero, somewhat tricky"""
    start, stop =  (0, start) if stop is None else  (start, stop)
    # allow for decrement
    while start > stop if step<0 else start < stop:
        yield start   # makes this a generator for new start value
        start += step

# test
print qrange(0, 10, 2)        # <generator object at 0x009D5E68>
print list(qrange(0, 10, 2))  # [0, 2, 4, 6, 8]
print list(qrange(10,0, -1))
print list(qrange(0,10,-1))

Specialties:
IT/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

This has problem of accumulating error during repeated summing and ends up for example giving 51 values for qrange(5, step=0.1). Would need to stop near the end not only after the end (-delta or +delta)

There is ready alternative as long as you have numpy: numpy.arange.

import numpy
# qrange( [start,] stop[, step] ) is a generator, works similar to xrange()
delta = 1e-6
def qrange(start, stop=None, step=1):
    """if start is missing it defaults to zero, somewhat tricky"""
    start, stop =  (0, start) if stop is None else  (start, stop)
    # allow for decrement
    while start > stop + delta if step<0 else start < stop - delta:
        yield start   # makes this a generator for new start value
        start += step

# test
print qrange(0, 10, 2)        # <generator object at 0x009D5E68>
print list(qrange(0, 10, 2))  # [0, 2, 4, 6, 8]
vals = list(qrange(5, step = 0.1))
vals2 = list(numpy.arange(0,5,0.1))
print 'qrange', len(vals)
print vals
print 'arange', len(vals2)
print vals2

Edited 5 Years Ago by pyTony: arange

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.