using range() in for loops

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Apr 5 11:23:23 EDT 2006


On Wed, 05 Apr 2006 16:21:02 +0200, Georg Brandl wrote:

> Because of backwards compatibility. range() returns a list, xrange() an
> iterator: list(xrange(...)) will give the same results as range(...).

Georg is pretty much correct in his explanation, but just to dot all the
I's and cross all the T's, we should explain that xrange() doesn't return
an iterator, it returns a special xrange object:

>>> x = xrange(1000)
>>> type(x)
<type 'xrange'>

xrange existed as a special bit of magic before Python supported
iterators. While xrange objects behave (sort of) like iterators, they
aren't quite the same. For instance, they don't have a next attribute:

>>> x.next
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'xrange' object has no attribute 'next'

whereas iterators do:

>>> i = iter(range(1000))
>>> i.next
<method-wrapper object at 0xf7054d2c>

Likewise, you can get random access to the items in an xrange object:

>>> x[500]
500

but not in iterators:

>>> i[500]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsubscriptable object



-- 
Steven.




More information about the Python-list mailing list