Re: What is xrange?



On 29/07/11 21:36, Billy Mays wrote:
Is xrange not a generator? I know it doesn't return a tuple or list,
so what exactly is it? Y doesn't ever complete, but x does.

x = (i for i in range(10))
y = xrange(10)

print "===X==="
while True:
for i in x:
print i
break
else:
break

print "===Y==="
while True:
for i in y:
print i
break
else:
break

Every for loop calls gets a new iterator from the object you're
iterating over. (__iter__) -- Apparently, xrange is implemented in such
a way (as are lists) that you can iterate over the object many times,
while each generator object (and how could it be otherwise can only be
iterated over once. What is xrange(foo)? It is an object that supports
list-like indices, the iterator protocol, and probably a few other
things that you will find in the stdlib docs. Generators also support
the iterator protocol, but that's about as far as the similarity goes
(in general)

- Thomas
.