What is xrange?

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat Jul 30 20:18:30 EDT 2011


Brian Blais wrote:
> On Jul 29, 2011, at 9:22 PM, Steven D'Aprano wrote:
> 
>>Billy Mays wrote:
>>
>>>Is xrange not a generator?  I know it doesn't return a tuple or list, so
>>>what exactly is it?

It's an iterable object.

There are advantages in having xrange (or range in python3) return
an iterable object, rather than creating an iterator directly.
One of them is that you can iterate over the same object more
than once.

This can be useful if you're iterating over a multi-dimensional
space of some kind. Some efficiency can be gained by pre-creating
an xrange object for each of the inner loops and re-using them.

-- 
Greg



More information about the Python-list mailing list