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
.



Relevant Pages

  • Re: need help on need help on generator...
    ... A generator function, ... way to make sure you have an iterator is to call iteron something; ... > there's such a thing in Python (... ... My prediction is that even Python 3000 will be strict. ...
    (comp.lang.python)
  • Re: generator slides review
    ... The use is assert in the first slide seem bad in a couple of different ... just an iterator. ... Generator functions return generators, ... bizarre and buggy. ...
    (comp.lang.python)
  • Re: Callable generators (PEP 288: Generator Attributes, again)
    ... >francisgavila@yahoo.com (Francis Avila) wrote in message ... >I looked at that PEP few months ago and I came out with an iterator class. ... >Wrapping the generator in the class, I can pass parameters to it (in ...
    (comp.lang.python)
  • Re: Callable generators (PEP 288: Generator Attributes, again)
    ... > I'm suggesting the PEP's functionality, not its syntax and semantics. ... > iterator is called, behaving like a state-persistent callable function. ... do think an iterator as something which it obtained by "instantiating" ... > Here's an efficient reversable generator: ...
    (comp.lang.python)
  • Re: Assigning generator expressions to ctype arrays
    ... you've just blown away the entire iterator for no good reason. ... the generator on the right hand side is unpacked into ... atomicity is important for this case. ... some elements of the ctypes array, that the programmer was in fact ...
    (comp.lang.python)