What is xrange?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jul 29 21:22:50 EDT 2011

Billy Mays wrote:

> Is xrange not a generator?  I know it doesn't return a tuple or list, so
> what exactly is it?  

xrange pre-dates generators by approximately forever. It returns a
special "xrange object", which generates values suitable for use in
for-loops using the old __getitem__ protocol.

You can consider xrange to be implemented something vaguely like this:

class My_xrange:
    def __init__(self, start, end=None, step=1):
        if end is None:
            end = start
            start = 0
        self.start = start
        self.end = end
        self.step = step
    def __getitem__(self, index):
        if self.step != 1:
            raise NotImplementedError('too lazy to support step values')
        start, end = self.start, self.end
        if start <= index < end:
            return start + index
        raise IndexError('out of range')

> Y doesn't ever complete, but x does. 
> x = (i for i in range(10))

That is better written as iter(range(10)).

> y = xrange(10)

Y doesn't complete because xrange objects are restartable. The for-loop ends
up using the original iteration protocol:

i = y[0]
i = y[1]
i = y[2]

until IndexError is raised. You break after calling y[0], but the next loop
starts at y[0] again, and so you never progress beyond the first item in
the xrange object.


More information about the Python-list mailing list