Welcome, guest | Sign In | My Account | Store | Cart

This is your standard vanilla range functions, converted to work as an iterator: UPDATE: xrange already does that. So feel free to ignore this.

Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def irange(start, stop=None, step=None):
    '''Return a range - as iterator.'''
    if stop == None:
        start, stop = 0, start
    if stop > start:
        _comp = lambda x, y: x <= y
        step = step or 1
    else:
        _comp = lambda x, y: x >= y
        step = step or -1
    if _comp(step, 0): # Safeguard: Wrong way => empty range
        raise StopIteration
    while _comp(start, stop):
        yield start
        start += step

One thing that has long puzzled me about python is its awkward for i in range(...) construct. Not the look of it, mind you - syntactically it is, IMHO, most elegant. But it may take lots of memory, if the range is very big.

The thing that seems to be missing from the itertools package is an "irange" function that does the same as range, only with iterators. So, here you have it.

Note: It even does one thing "better" than the original range, namely automagically choosing a negative step if stop < start and no step is specified. If you dislike this, you can move the "step = step or 1" out of the if and remove the "step = step or -1". Happy iterating!

UPDATE: I should have looked into the function reference...

Created by Andreas Kloss on Tue, 31 Aug 2004 (PSF)
Python recipes (4591)
Andreas Kloss's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks